1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
//! Check signatures in authentication headers, find the correct agent. Authorization is done in Hierarchies
use crate::{
agents::{decode_base64, ForAgent},
errors::AtomicResult,
urls,
utils::check_timestamp_in_past,
Storelike,
};
/// Set of values extracted from the request.
/// Most are coming from headers.
#[derive(serde::Deserialize)]
pub struct AuthValues {
// x-atomic-public-key
#[serde(rename = "https://atomicdata.dev/properties/auth/publicKey")]
pub public_key: String,
// x-atomic-timestamp
#[serde(rename = "https://atomicdata.dev/properties/auth/timestamp")]
pub timestamp: i64,
// x-atomic-signature
// Base64 encoded public key from `subject_url timestamp`
#[serde(rename = "https://atomicdata.dev/properties/auth/signature")]
pub signature: String,
#[serde(rename = "https://atomicdata.dev/properties/auth/requestedSubject")]
pub requested_subject: String,
#[serde(rename = "https://atomicdata.dev/properties/auth/agent")]
pub agent_subject: String,
}
/// Checks if the signature is valid for this timestamp.
/// Does not check if the agent has rights to access the subject.
#[tracing::instrument(skip_all)]
pub fn check_auth_signature(subject: &str, auth_header: &AuthValues) -> AtomicResult<()> {
let agent_pubkey = decode_base64(&auth_header.public_key)?;
let message = format!("{} {}", subject, &auth_header.timestamp);
let pubkey_bytes: [u8; 32] = agent_pubkey
.try_into()
.map_err(|_| "Ed25519 public key must be 32 bytes")?;
let verifying_key = ed25519_dalek::VerifyingKey::from_bytes(&pubkey_bytes)
.map_err(|e| format!("Invalid public key: {}", e))?;
let signature_bytes = decode_base64(&auth_header.signature)?;
let sig_bytes: [u8; 64] = signature_bytes
.try_into()
.map_err(|_| "Ed25519 signature must be 64 bytes")?;
let sig = ed25519_dalek::Signature::from_bytes(&sig_bytes);
use ed25519_dalek::Verifier;
let result = verifying_key.verify(message.as_bytes(), &sig);
if result.is_err() {
// In multi-tenant environments, the client might sign the full URL or just the path.
// If it's a full URL, try checking just the path (with and without query params) as well.
if let Ok(url) = url::Url::parse(subject) {
let path = url.path();
let query = url.query().map(|q| format!("?{}", q)).unwrap_or_default();
// Try path+query (e.g. /setup?reset=true)
let path_and_query = format!("{}{}", path, query);
if path_and_query != subject {
let message_path = format!("{} {}", path_and_query, &auth_header.timestamp);
if verifying_key.verify(message_path.as_bytes(), &sig).is_ok() {
return Ok(());
}
}
// Try full URL without query params (e.g. client signed http://host/setup but URL has ?params)
if url.query().is_some() {
let mut url_no_query = url.clone();
url_no_query.set_query(None);
let message_no_query = format!("{} {}", url_no_query, &auth_header.timestamp);
if verifying_key
.verify(message_no_query.as_bytes(), &sig)
.is_ok()
{
return Ok(());
}
// Also try path-only without query params
let message_path_no_query = format!("{} {}", path, &auth_header.timestamp);
if verifying_key
.verify(message_path_no_query.as_bytes(), &sig)
.is_ok()
{
return Ok(());
}
}
}
// If we haven't returned Ok, return the original error.
return Err(format!(
"Incorrect signature for auth headers. This could be due to an error during signing or serialization of the commit. Compare this to the serialized message in the client: {}",
message,
)
.into());
}
Ok(())
}
const ACCEPTABLE_TIME_DIFFERENCE: i64 = 10000;
/// Get the Agent's subject from [AuthValues]
/// Checks if the auth headers are correct, whether signature matches the public key, whether the timestamp is valid.
/// by default, returns the public agent
#[tracing::instrument(skip_all)]
pub async fn get_agent_from_auth_values_and_check(
auth_header_values: Option<AuthValues>,
store: &impl Storelike,
) -> AtomicResult<ForAgent> {
if let Some(auth_vals) = auth_header_values {
// If there are auth headers, check 'em, make sure they are valid.
check_auth_signature(&auth_vals.requested_subject, &auth_vals)
.map_err(|e| format!("Error checking authentication headers. {}", e))?;
// check if the timestamp is valid
check_timestamp_in_past(auth_vals.timestamp, ACCEPTABLE_TIME_DIFFERENCE)?;
// check if the public key belongs to the agent
// For DID subjects, we need to fetch the agent resource locally
// unless it's a DID based on the public key, in which case we can verify it directly.
let agent_subject = crate::Subject::from_raw(auth_vals.agent_subject.trim(), None);
let public_key_trimmed = auth_vals.public_key.trim();
if agent_subject.is_did() {
// The DID subject embeds the agent's public key
// (`did:ad:agent:{pubkey}`) and the auth header carries the same
// key. The two may use different base64 alphabets — the url-safe
// alphabet (the new default) vs the legacy standard alphabet
// (`+` `/` `=`) — so a raw-string `ends_with` wrongly rejects a key
// whose decoded BYTES are identical. Compare the decoded bytes.
let did_pubkey = agent_subject
.as_str()
.strip_prefix(crate::subject::DID_AD_AGENT_PREFIX)
.unwrap_or_else(|| agent_subject.as_str());
if public_keys_match(did_pubkey, public_key_trimmed) {
return Ok(ForAgent::AgentSubject(agent_subject));
} else {
return Err(format!(
"The public key in the auth headers '{}' does not match the DID subject '{}'",
public_key_trimmed, auth_vals.agent_subject
)
.into());
}
}
let agent_resource = store.get_resource(&agent_subject).await?;
let found_public_key = agent_resource.get(urls::PUBLIC_KEY)?;
if !public_keys_match(found_public_key.to_string().trim(), public_key_trimmed) {
Err(
"The public key in the auth headers does not match the public key in the agent"
.to_string()
.into(),
)
} else {
Ok(ForAgent::AgentSubject(agent_subject))
}
} else {
Ok(ForAgent::Public)
}
}
/// Two base64-encoded public keys match if their decoded bytes are equal.
/// Tolerates differing base64 alphabets (url-safe — the new default — vs the
/// legacy standard alphabet with `+` `/` `=`), so an agent whose DID or stored
/// key was minted with one alphabet still authenticates against an auth header
/// using the other. Falls back to `false` if either string can't be decoded.
fn public_keys_match(a: &str, b: &str) -> bool {
if a == b {
return true;
}
matches!(
(
crate::agents::decode_base64(a),
crate::agents::decode_base64(b),
),
(Ok(da), Ok(db)) if da == db
)
}
// fn get_agent_from_value_index() {
// let map = store.get_prop_subject_map(&auth_vals.public_key)?;
// let agents = map.get(crate::urls::PUBLIC_KEY).ok_or(format!(
// "No agents for this public key: {}",
// &auth_vals.public_key
// ))?;
// // TODO: This is unreliable, as this will break if multiple atoms with the same public key exist.
// if agents.len() > 1 {
// return Err("Multiple agents for this public key".into());
// } else if let Some(found) = agents.iter().next() {
// for_agent = Some(found.to_string());
// }
// }
#[cfg(test)]
mod test {
use super::public_keys_match;
/// The same ed25519 key, encoded in the legacy standard base64 alphabet
/// (as embedded in a legacy agent DID) and in the url-safe alphabet (as
/// sent in modern auth headers), must be recognised as the same key —
/// otherwise legacy agents can't authenticate (WS AUTH fails → the client
/// never gets AUTH_OK → it falls offline and edits never sync).
#[test]
fn public_keys_match_across_base64_alphabets() {
let standard = "gJRZVTGPngaG3mSPA/e6LEewKixYpZtuUYQhNg+t7Y4=";
let url_safe = "gJRZVTGPngaG3mSPA_e6LEewKixYpZtuUYQhNg-t7Y4";
assert!(
public_keys_match(standard, url_safe),
"standard and url-safe encodings of the same key should match"
);
assert!(public_keys_match(standard, standard));
assert!(public_keys_match(url_safe, url_safe));
}
#[test]
fn public_keys_match_rejects_different_keys() {
let a = "gJRZVTGPngaG3mSPA_e6LEewKixYpZtuUYQhNg-t7Y4";
let b = "AAAAVTGPngaG3mSPA_e6LEewKixYpZtuUYQhNg-t7Y4";
assert!(!public_keys_match(a, b));
}
}