~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

Rules found by rebuilding lifecycle and OAuth scopes from the spec alone, with the server fixed to them

Merged chadtmiller.com asked to merge into gatespeed from chadtmiller.com/monolith:lifegaps-s
crates/pds-server/src/lifecycle/tests.rs+337−0
@@ -1792,3 +1792,340 @@ async fn a_deletion_cut_short() {
}
let _ = std::fs::remove_dir_all(&work);
}
/// The PLC directory cannot be read: `validDid` is `false`, the answer
/// `200`; an activation, by the owner or the admin, of an account or of a
/// DID no account has, is `502`, and a takedown lifted in the same call
/// stays lifted.
#[tokio::test]
async fn the_directory_down() {
let mut e = Env::new("life-plc-down").await;
let (did, token) = create(&e.s, "alice").await;
e.call(DEACTIVATE, Some(&token), json!({})).await.unwrap();
e.takedown(&did, true).await.unwrap();
let plc = std::mem::replace(&mut e.plc, "http://127.0.0.1:1".into());
e.reopen();
let got = e.call(CHECK, Some(&token), Json::Null).await.unwrap();
assert_eq!(
(&got["validDid"], &got["activated"]),
(&json!(false), &json!(false))
);
// The directory before the takedown.
assert_eq!(
e.call(ACTIVATE, Some(&token), Json::Null).await,
Err("UpstreamFailure".into())
);
let before = e.events().len();
let both = json!({ "subject": { "$type": REPO_REF, "did": did }, "takedown": { "applied": false }, "deactivated": { "applied": false } });
assert_eq!(e.admin(UPDATE, both).await, Err("UpstreamFailure".into()));
let state = e.admin_query(&[("did", &did)]).await.unwrap();
assert_eq!(
(&state["takedown"], &state["deactivated"]),
(&json!({ "applied": false }), &json!({ "applied": true }))
);
assert_eq!(
e.events()[before..].iter().map(brief).collect::<Vec<_>>(),
[format!("account {did} false deactivated")]
);
let nobody = json!({ "subject": { "$type": REPO_REF, "did": "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa" }, "deactivated": { "applied": false } });
assert_eq!(e.admin(UPDATE, nobody).await, Err("UpstreamFailure".into()));
assert_eq!(e.events().len(), before + 1);
// Deactivating reads no directory.
e.call(DEACTIVATE, Some(&token), json!({})).await.unwrap();
// Up again, it is activated.
e.plc = plc;
e.reopen();
e.call(ACTIVATE, Some(&token), Json::Null).await.unwrap();
assert_eq!(
e.call(CHECK, Some(&token), Json::Null).await.unwrap()["validDid"],
json!(true)
);
}
/// A deleted account's activation, by its token or the admin: its token,
/// its body, then its DID document, whose rotation keys and endpoint are
/// looked at before its signing key, which is gone.
#[tokio::test]
async fn a_deleted_account_activated() {
let e = Env::new("life-deleted-activate").await;
let (did, token) = create(&e.s, "alice").await;
let app = app_session(&e, &token, "alice.test").await;
e.call(REQUEST_DELETE, Some(&token), Json::Null)
.await
.unwrap();
e.call(
DELETE,
None,
json!({ "did": did, "password": "alice-pw", "token": last_token(&e.sink) }),
)
.await
.unwrap();
let activate = json!({ "subject": { "$type": REPO_REF, "did": did }, "deactivated": { "applied": false } });
assert_eq!(
e.call(ACTIVATE, Some(&app), Json::Null).await,
Err("InvalidToken".into())
);
assert_eq!(
e.call(ACTIVATE, Some(&token), json!({})).await,
Err("InvalidRequest".into())
);
// Its document still names this server.
assert_eq!(
e.call(ACTIVATE, Some(&token), Json::Null).await,
Err("InternalServerError".into())
);
assert_eq!(
e.admin(UPDATE, activate.clone()).await,
Err("InternalServerError".into())
);
// Moved elsewhere.
let moved = reqwest::Client::new()
.put(format!("{}/{did}/data", e.plc))
.body("https://elsewhere.example")
.send()
.await
.unwrap();
assert!(moved.status().is_success());
assert_eq!(
e.call(ACTIVATE, Some(&token), Json::Null).await,
Err("InvalidRequest".into())
);
assert_eq!(
e.admin(UPDATE, activate).await,
Err("InvalidRequest".into())
);
}
/// A record's `uri` that names no record, of an account here, taken down
/// or not: `updateSubjectStatus` takes down nothing, `getSubjectStatus` is
/// `400 NotFound`; a handle as its authority is `500` to both.
#[tokio::test]
async fn uris_naming_no_record() {
let e = Env::new("life-uris").await;
let (did, token) = create(&e.s, "alice").await;
let rec = e
.call(
"com.atproto.repo.putRecord",
Some(&token),
put(&did, "one", json!({ "n": 1 })),
)
.await
.unwrap();
let strong = |uri: &str| json!({ "$type": STRONG_REF, "uri": uri, "cid": rec["cid"] });
for down in [false, true] {
e.takedown(&did, down).await.unwrap();
for uri in [format!("at://{did}"), format!("at://{did}/a.b.c")] {
let got = e
.admin(
UPDATE,
json!({ "subject": strong(&uri), "takedown": { "applied": true, "ref": "x" } }),
)
.await
.unwrap();
assert_eq!(got["subject"]["uri"], json!(uri));
assert_eq!(
e.admin_query(&[("uri", &uri)]).await,
Err("NotFound".into()),
"{uri}"
);
}
let status = e
.admin_query(&[("uri", rec["uri"].as_str().unwrap())])
.await
.unwrap();
assert_eq!(status["takedown"], json!({ "applied": false }));
}
for uri in [
"at://alice.test/a.b.c/one",
"at://nobody.test/a.b.c/one",
"at://alice.test",
] {
assert_eq!(
e.admin_query(&[("uri", uri)]).await,
Err("InternalServerError".into()),
"{uri}"
);
}
assert_eq!(
e.admin_query(&[("uri", "at://did:plc:aaaaaaaaaaaaaaaaaaaaaaaa/a.b.c/one")])
.await,
Err("NotFound".into())
);
}
/// The email methods, `getAccountInviteCodes` and the preferences, of an
/// account in each state: refused with the token, before the input, a
/// taken-down account `401 AccountTakedown` and a deleted one `403
/// AccountNotFound`, with no mail sent.
#[tokio::test]
async fn own_calls_by_state() {
let e = Env::new("life-own-rows").await;
let mut c = crate::Config {
mailer: crate::email::Mailer::sink(&e.sink),
..config(&e.plc)
};
c.proxy.appview = Some(crate::proxy::AppView {
url: "http://127.0.0.1:1".into(),
did: "did:web:appview.test".into(),
});
let dir = scratch("life-own-rows-app");
let s: Shared = Arc::new(Service::open(&dir, c).unwrap());
let (did, token) = create(&s, "alice").await;
let app = {
let pw = call(
&s,
"com.atproto.server.createAppPassword",
Some(&token),
json!({ "name": "app" }),
)
.await
.unwrap()["password"]
.clone();
tokens(
&call(
&s,
LOGIN,
None,
json!({ "identifier": "alice.test", "password": pw }),
)
.await
.unwrap(),
)
.0
};
/// A call: its method, its parameters and its input.
type Row<'a> = (&'a str, &'a [(String, String)], Json);
async fn rows(s: &Shared, token: &str) -> Vec<String> {
let none: &[(String, String)] = &[];
let bad = [("includeUsed".to_string(), "nope".to_string())];
let calls: Vec<Row> = vec![
(
"com.atproto.server.requestEmailConfirmation",
none,
Json::Null,
),
(
"com.atproto.server.confirmEmail",
none,
json!({ "email": 5 }),
),
("com.atproto.server.requestEmailUpdate", none, Json::Null),
(
"com.atproto.server.updateEmail",
none,
json!({ "email": 5 }),
),
("com.atproto.server.getAccountInviteCodes", none, Json::Null),
("com.atproto.server.getAccountInviteCodes", &bad, Json::Null),
("app.bsky.actor.getPreferences", none, Json::Null),
(
"app.bsky.actor.putPreferences",
none,
json!({ "preferences": 5 }),
),
(
"app.bsky.actor.putPreferences",
none,
json!({ "preferences": [] }),
),
];
let mut out = Vec::new();
for (nsid, p, b) in calls {
out.push(
call_with(s, nsid, Some(token), p, b)
.await
.map_or_else(|x| x, |_| "ok".to_string()),
);
}
out
}
let (inv, td, nf) = ("InvalidRequest", "AccountTakedown", "AccountNotFound");
assert_eq!(
rows(&s, &token).await,
["ok", inv, "ok", inv, "ok", inv, "ok", inv, "ok"]
);
call(&s, DEACTIVATE, Some(&token), json!({})).await.unwrap();
assert_eq!(
rows(&s, &token).await,
["ok", inv, "ok", inv, "NotFound", inv, "ok", inv, "ok"]
);
let mailed = sent(&e.sink).len();
let takedown = json!({ "subject": { "$type": REPO_REF, "did": did }, "takedown": { "applied": true, "ref": "r" } });
call_raw(
&s,
UPDATE,
Bearer::of(Some(&admin_header())),
&[],
&takedown.to_string(),
)
.await
.unwrap();
assert_eq!(
rows(&s, &token).await,
[td, td, td, td, td, inv, "ok", td, td]
);
// The token's own checks first.
for nsid in [
"com.atproto.server.requestEmailUpdate",
"com.atproto.server.getAccountInviteCodes",
] {
assert_eq!(
call(&s, nsid, Some(&app), Json::Null).await,
Err("InvalidToken".into()),
"{nsid}"
);
}
// A takendown session's token works for getPreferences alone.
let login =
json!({ "identifier": "alice.test", "password": "alice-pw", "allowTakendown": true });
let down = tokens(&call(&s, LOGIN, None, login).await.unwrap()).0;
assert_eq!(
call(&s, "app.bsky.actor.getPreferences", Some(&down), Json::Null).await,
Ok(json!({ "preferences": [] }))
);
for nsid in [
"app.bsky.actor.putPreferences",
"com.atproto.server.requestEmailConfirmation",
] {
assert_eq!(
call(&s, nsid, Some(&down), json!({ "preferences": [] })).await,
Err("InvalidToken".into()),
"{nsid}"
);
}
assert_eq!(sent(&e.sink).len(), mailed);
// Deleted.
let lift =
json!({ "subject": { "$type": REPO_REF, "did": did }, "takedown": { "applied": false } });
call_raw(
&s,
UPDATE,
Bearer::of(Some(&admin_header())),
&[],
&lift.to_string(),
)
.await
.unwrap();
call(&s, REQUEST_DELETE, Some(&token), Json::Null)
.await
.unwrap();
call(
&s,
DELETE,
None,
json!({ "did": did, "password": "alice-pw", "token": last_token(&e.sink) }),
)
.await
.unwrap();
let mailed = sent(&e.sink).len();
assert_eq!(
rows(&s, &token).await,
[nf, nf, nf, nf, nf, inv, "NotFound", nf, nf]
);
assert_eq!(
call(&s, "app.bsky.actor.getPreferences", Some(&down), Json::Null).await,
Err("NotFound".into())
);
assert_eq!(sent(&e.sink).len(), mailed);
let _ = std::fs::remove_dir_all(&dir);
}
crates/pds-server/src/scopes/tests.rs+49−0
@@ -672,6 +672,32 @@ async fn blob_uploads() {
)
.await;
assert_eq!(answer(&big).1, "PayloadTooLarge");
// Each byte of the header is its Latin-1 character, lowered, then UTF-8.
for (bytes, s) in [
(&b"image/p\xC9ng"[..], "blob:image/p%C3%A9ng"),
(&b"x/\xC3\x89"[..], "blob:x/%C3%A3%C2%89"),
(&b"\xC9/x"[..], "blob:%C3%A9/x"),
] {
let proof = c.proof("POST", "com.atproto.repo.uploadBlob", true);
let r = srv
.request("POST", "/xrpc/com.atproto.repo.uploadBlob")
.body(b"some bytes".to_vec())
.header(
"content-type",
reqwest::header::HeaderValue::from_bytes(bytes).unwrap(),
)
.header("authorization", format!("DPoP {}", c.access))
.header("dpop", proof);
let g = got(r).await;
if let Some(n) = g.header("dpop-nonce") {
c.app.nonce = Some(n);
}
if s.starts_with("blob:image/") {
ok(&g);
} else {
lacks(&g, s);
}
}
let _ = std::fs::remove_dir_all(&dir);
}
@@ -870,6 +896,29 @@ async fn reads() {
(g.status, g.error(), g.header("dpop-nonce")),
(401, "AuthenticationRequired".into(), None)
);
// A `DPoP` header that is not two words is a header of a bad form, first.
for (header, status, name) in [
("DPoP", 400, "InvalidToken"),
("DPoP a b", 400, "InvalidToken"),
("dpop abc", 401, "AuthenticationRequired"),
] {
let g = c
.send(
"POST",
"com.atproto.server.createAccount",
"",
Some("application/json"),
b"{}".to_vec(),
Some(header.into()),
None,
)
.await;
assert_eq!(
(g.status, g.error(), g.header("dpop-nonce")),
(status, name.into(), None),
"{header}"
);
}
let _ = std::fs::remove_dir_all(&dir);
}
crates/pds-server/src/blobs.rs+14−1
@@ -1000,7 +1000,20 @@ async fn upload_blob(
if media.is_empty() {
return invalid("Request encoding (Content-Type) required but not provided");
}
crate::scopes::may(call.bearer, &crate::scopes::Need::Blob(&media))?;
// What the scope needs reads each byte of the header as its Latin-1
// character, as the refusal names it (`spec/OAUTH-SCOPES.md`).
let raw = headers
.get(header::CONTENT_TYPE)
.map(|v| v.as_bytes())
.unwrap_or_default();
let latin1: String = raw
.split(|&b| b == b';')
.next()
.unwrap_or_default()
.iter()
.map(|&b| char::from(b))
.collect();
crate::scopes::may(call.bearer, &crate::scopes::Need::Blob(&latin1))?;
let too_large = || err(413, "PayloadTooLarge", "request entity too large");
let length = headers
.get(header::CONTENT_LENGTH)
crates/pds-server/src/invites.rs+1−0
@@ -330,6 +330,7 @@ fn get_account_invite_codes(
p: &Map<String, Json>,
) -> Result<Resp, XrpcError> {
let t = full_access_token(s, call.bearer)?;
crate::lifecycle::gate(s, call.nsid, &t.did)?;
let include_used = p.get("includeUsed").and_then(Json::as_bool).unwrap_or(true);
let st = s.invites.lock();
let codes: Vec<Json> = st
crates/pds-server/src/lib.rs+14−8
@@ -838,13 +838,15 @@ async fn serve(svc: &Shared, call: &Call<'_>) -> Result<Resp, XrpcError> {
let mut shown = Shown::default();
// A query changes nothing, so it may pay once it has run: its
// token, checked within it, costs nothing if it is refused, nor
// a scope checked with it (`getServiceAuth`'s `rpc`).
// a scope checked with it (`getServiceAuth`'s `rpc`), nor its
// account's state checked with it (`lifecycle::with_token`).
let out =
lifecycle::gate_query(svc, call, &p).and_then(|()| f(svc, call, &mut shown, &p));
if !out
.as_ref()
.is_err_and(|e| token_error(e) || e.name == "ScopeMissingError")
{
if !out.as_ref().is_err_and(|e| {
token_error(e)
|| e.name == "ScopeMissingError"
|| lifecycle::refused_with_token(call.nsid, e)
}) {
limits::charge(svc, call, None, None)?;
}
shown.durable().await?;
@@ -900,13 +902,17 @@ async fn serve(svc: &Shared, call: &Call<'_>) -> Result<Resp, XrpcError> {
_ => Map::new(),
};
// It pays once its token, what its scope needs of the service it
// goes to, and its input are checked, as any other call does,
// before it goes anywhere.
// goes to, its account's state if it is checked with the token,
// and its input are checked, as any other call does, before it
// goes anywhere.
let did = match proxy::needs_token(call.nsid) {
true => Some(sessions::access_token(svc, call.bearer)?.did),
true => Some(preferences::token(svc, call.nsid, call.bearer)?.did),
false => None,
};
proxy::scope(svc, call)?;
if let Some(did) = did.as_deref().filter(|_| lifecycle::with_token(call.nsid)) {
lifecycle::gate(svc, call.nsid, did)?;
}
let p = match m.kind {
Kind::Procedure => filled_input(call, m)?,
_ => p,
crates/pds-server/src/lifecycle.rs+116−49
@@ -353,16 +353,26 @@ fn row(nsid: &str) -> Option<Row> {
"com.atproto.server.createAppPassword"
| "com.atproto.repo.uploadBlob"
| "com.atproto.identity.updateHandle"
| "com.atproto.server.requestAccountDelete" => own(TAKEDOWN, NOT_FOUND),
| "com.atproto.server.requestAccountDelete"
| "com.atproto.server.requestEmailConfirmation"
| "com.atproto.server.confirmEmail"
| "com.atproto.server.requestEmailUpdate"
| "com.atproto.server.updateEmail"
| "app.bsky.actor.putPreferences" => own(TAKEDOWN, NOT_FOUND),
"com.atproto.server.getAccountInviteCodes" => Row {
of: Of::Token,
deactivated: Answer::Refuse(400, "NotFound"),
takendown: TAKEDOWN,
deleted: NOT_FOUND,
},
"app.bsky.actor.getPreferences" => own(PASS, Answer::Refuse(400, "NotFound")),
"com.atproto.identity.getRecommendedDidCredentials" => {
own(PASS, Answer::Refuse(500, "InternalServerError"))
}
"com.atproto.server.checkAccountStatus" => own(PASS, Answer::Refuse(400, "NotFound")),
"com.atproto.server.deactivateAccount" => own(PASS, INVALID),
// Taken down, it is refused once its DID document is checked.
"com.atproto.server.activateAccount" => {
own(PASS, Answer::Refuse(500, "InternalServerError"))
}
// `activateAccount` checks its account's state itself, after its DID
// document (`activate`, `activate_gone`).
// A write's is the account of its `repo` (`write_repo`).
"com.atproto.repo.createRecord"
| "com.atproto.repo.putRecord"
@@ -437,7 +447,9 @@ pub(crate) fn gate(s: &Service, nsid: &str, did: &str) -> Result<(), XrpcError>
/// Whether a call of `nsid` has its state checked with its token, before its
/// input and rate limits: the account's own calls a taken-down account is
/// refused with `401 AccountTakedown` and a deleted one with `403
/// AccountNotFound`, as the reference refuses them with the token.
/// AccountNotFound`, as the reference refuses them with the token, and
/// `getPreferences`, which has no input. A query among them checks its
/// token, and then its state, itself (`getAccountInviteCodes`).
pub(crate) fn with_token(nsid: &str) -> bool {
matches!(
nsid,
@@ -445,9 +457,22 @@ pub(crate) fn with_token(nsid: &str) -> bool {
| "com.atproto.repo.uploadBlob"
| "com.atproto.identity.updateHandle"
| "com.atproto.server.requestAccountDelete"
| "com.atproto.server.requestEmailConfirmation"
| "com.atproto.server.confirmEmail"
| "com.atproto.server.requestEmailUpdate"
| "com.atproto.server.updateEmail"
| "com.atproto.server.getAccountInviteCodes"
| "app.bsky.actor.getPreferences"
| "app.bsky.actor.putPreferences"
)
}
/// Whether an error is the refusal of a call's account's state made with
/// its token, which costs the call nothing of the rate limits.
pub(crate) fn refused_with_token(nsid: &str, e: &XrpcError) -> bool {
with_token(nsid) && matches!(e.name, "AccountTakedown" | "AccountNotFound")
}
/// The state check of a query once its parameters are checked: of its
/// token's account, if its token is one, which the query checks itself if
/// not; or of the account a parameter names, if any has it, which the query
@@ -459,6 +484,7 @@ pub(crate) fn gate_query(s: &Service, call: &Call, p: &Map<String, Json>) -> Res
return Ok(());
};
match r.of {
Of::Token if with_token(call.nsid) => Ok(()),
Of::Token => match s.auth(call.bearer) {
Auth::Account(did) => answer_of(s, &r, &did),
_ => Ok(()),
@@ -667,39 +693,56 @@ async fn announce(s: &Shared, did: &str) -> Result<(), XrpcError> {
settle(s, n, landing).await
}
/// The PLC directory's current data for `did`: none if it does not know the
/// DID, `502 UpstreamFailure` if it cannot be read.
async fn did_data(s: &Service, did: &str) -> Result<Option<Json>, XrpcError> {
let url = format!("{}/{did}/data", s.config.plc_url.trim_end_matches('/'));
crate::plc::document(&s.http, &url).await.or_else(|why| {
crate::ops::failed_for(
crate::ops::Level::Error,
"reading a DID's data failed",
did,
why,
);
err(
502,
"UpstreamFailure",
"The PLC directory could not be reached",
)
})
}
/// Whether a DID's data names this server: its rotation keys include the
/// server's and its PDS is this one, looked at first, then its signing key
/// is `signing`, if the account has one still.
fn names_server(s: &Service, data: &Json, signing: Option<&str>) -> bool {
let rotation = crate::plc::did_key(s.config.rotation_key.verifying_key());
data["rotationKeys"]
.as_array()
.is_some_and(|keys| keys.iter().any(|k| *k == json!(rotation)))
&& data["services"]["atproto_pds"]["endpoint"] == json!(s.config.public_url)
&& signing.is_none_or(|k| data["verificationMethods"]["atproto"] == json!(k))
}
/// Whether the PLC directory's current data for the account's DID names
/// this server: its PDS, its signing key, and the server's rotation key.
async fn valid_did(s: &Service, a: &Account) -> Result<bool, XrpcError> {
let url = format!("{}/{}/data", s.config.plc_url.trim_end_matches('/'), a.did);
let data = match crate::plc::document(&s.http, &url).await {
Ok(Some(d)) => d,
Ok(None) => return Ok(false),
Err(why) => {
crate::ops::failed_for(
crate::ops::Level::Error,
"reading a DID's data failed",
&a.did,
why,
);
return internal();
}
let Some(data) = did_data(s, &a.did).await? else {
return Ok(false);
};
let signing = crate::plc::did_key(read(&a.store).repo.verifying_key());
let rotation = crate::plc::did_key(s.config.rotation_key.verifying_key());
Ok(
data["services"]["atproto_pds"]["endpoint"] == json!(s.config.public_url)
&& data["verificationMethods"]["atproto"] == json!(signing)
&& data["rotationKeys"]
.as_array()
.is_some_and(|keys| keys.iter().any(|k| *k == json!(rotation))),
)
Ok(names_server(s, &data, Some(&signing)))
}
fn not_this_server<T>() -> Result<T, XrpcError> {
invalid("Requested DID does not match current DID document")
}
/// Activate an account, by its owner or the admin: refused if its DID
/// document does not name this server, then if it is taken down.
async fn activate(s: &Shared, a: &Account) -> Result<(), XrpcError> {
if !valid_did(s, a).await? {
return invalid("Requested DID does not match current DID document");
return not_this_server();
}
if read(&a.state).takedown.is_some() {
return err(400, "AccountNotFound", "Account has been taken down");
@@ -707,6 +750,17 @@ async fn activate(s: &Shared, a: &Account) -> Result<(), XrpcError> {
make(s, a, Change::Activate).await
}
/// Activate a DID no account here has, deleted or never made, by its
/// deleted account's token or the admin: its DID document is read as an
/// account's, but there is no signing key to find in it, and one that
/// otherwise names this server is `500`, as the reference answers it.
async fn activate_gone(s: &Service, did: &str) -> Result<(), XrpcError> {
match did_data(s, did).await? {
Some(data) if names_server(s, &data, None) => internal(),
_ => not_this_server(),
}
}
/// The token's account, which the gate found.
fn own(s: &Service, t: &Token) -> Result<Arc<Account>, XrpcError> {
s.account(&t.did).map_or_else(internal, Ok)
@@ -719,14 +773,17 @@ async fn deactivate_account(s: Shared, t: Token) -> Result<Resp, XrpcError> {
}
async fn activate_account(s: Shared, t: Token) -> Result<Resp, XrpcError> {
let a = own(&s, &t)?;
activate(&s, &a).await?;
match s.account(&t.did) {
Some(a) => activate(&s, &a).await?,
None => activate_gone(&s, &t.did).await?,
}
Ok(Resp::Nothing)
}
async fn check_account_status(s: Shared, t: Token) -> Result<Resp, XrpcError> {
let a = own(&s, &t)?;
let valid = valid_did(&s, &a).await?;
// A directory that cannot be read is answered as one that does not name this server.
let valid = valid_did(&s, &a).await.unwrap_or(false);
let (mut out, wal, n) = {
let st = read(&a.store);
let (expected, imported) = st.blobs.counts(s.limits.clock.now(), s.config.blob_ttl);
@@ -923,14 +980,7 @@ async fn update_subject_status(s: Shared, b: Map<String, Json>) -> Result<Resp,
Some(a) if on => make(&s, &a, Change::Deactivate { by_oauth: false }).await?,
Some(a) => activate(&s, &a).await?,
None if on => return invalid("Account not found"),
None => {
// As the reference answers a DID it no longer has the account of.
let url = format!("{}/{did}", s.config.plc_url.trim_end_matches('/'));
return match crate::plc::document(&s.http, &url).await {
Ok(None) => invalid("Account not found"),
_ => internal(),
};
}
None => activate_gone(&s, &did).await?,
}
}
if takedown.is_none() && b.get("deactivated").is_none() && ty == REPO_REF {
@@ -943,24 +993,37 @@ async fn update_subject_status(s: Shared, b: Map<String, Json>) -> Result<Resp,
Ok(Resp::Json(out))
}
/// An `at://` URI's DID, collection and record key; any other is none.
fn record_uri(uri: &str) -> Option<(&str, &str, &str)> {
/// An `at://` URI's authority, and the path `collection/rkey` of the record
/// it names, if it names one: none of its authority alone, or of a
/// collection and no key. Any other URI is none.
fn record_uri(uri: &str) -> Option<(&str, Option<String>)> {
let mut parts = uri.strip_prefix("at://")?.splitn(3, '/');
let (did, collection, rkey) = (parts.next()?, parts.next()?, parts.next()?);
(did.starts_with("did:") && !collection.is_empty() && !rkey.is_empty() && !rkey.contains('/'))
.then_some((did, collection, rkey))
let authority = parts.next().filter(|a| !a.is_empty())?;
let path = match (
parts.next().filter(|c| !c.is_empty()),
parts.next().filter(|k| !k.is_empty()),
) {
(Some(collection), Some(rkey)) if !rkey.contains('/') => {
Some(format!("{collection}/{rkey}"))
}
(_, Some(_)) => return None,
_ => None,
};
Some((authority, path))
}
/// Take down the record the repository now has at the URI's key, or lift
/// that: a key it does not hold changes nothing.
/// that: a key it does not hold changes nothing, nor a URI of an account
/// here that names no record. One whose authority is a handle, or a DID no
/// account here has, is `500`, as the reference answers it.
async fn take_record_down(s: &Shared, uri: &str, r: Option<String>) -> Result<(), XrpcError> {
let Some((did, collection, rkey)) = record_uri(uri) else {
let Some((did, path)) = record_uri(uri).filter(|(a, _)| a.starts_with("did:")) else {
return internal();
};
let Some(a) = s.account(did) else {
return internal();
};
let path = format!("{collection}/{rkey}");
let Some(path) = path else { return Ok(()) };
let (wal, n) = {
let mut st = write(&a.store);
not_deleted(&a)?;
@@ -1051,14 +1114,18 @@ async fn get_subject_status(s: Shared, p: Map<String, Json>) -> Result<Resp, Xrp
let out = json!({ "subject": { "$type": BLOB_REF, "did": a.did, "cid": cid }, "takedown": takedown_json(r) });
(out, st.wal.clone(), st.wal.written())
} else if let Some(uri) = uri {
let Some((did, collection, rkey)) = record_uri(uri) else {
let Some((did, path)) = record_uri(uri) else {
return not_found();
};
// As the reference answers a handle, whether or not an account has it.
if !did.starts_with("did:") {
return internal();
}
let Some(a) = s.account(did) else {
return not_found();
};
let Some(path) = path else { return not_found() };
let st = read(&a.store);
let path = format!("{collection}/{rkey}");
let Some(rec) = st.repo.records.get(&path) else {
return not_found();
};
crates/pds-server/src/preferences.rs+12−3
@@ -8,8 +8,8 @@
//! entry is on disk.
use crate::proxy::{self, Request};
use crate::sessions::{self, ACCESS};
use crate::{Handler, Resp, Shared, XrpcError, durable, internal, invalid, read, write};
use crate::sessions::{self, ACCESS, Bearer, Token};
use crate::{Handler, Resp, Service, Shared, XrpcError, durable, internal, invalid, read, write};
use pds_repo::data::{civil_from_days, datetime_millis};
use serde_json::{Map, Value as Json, json};
use std::collections::HashMap;
@@ -93,8 +93,17 @@ fn age(birth: i64, now: i64) -> i64 {
y - by - i64::from((m, d) < (bm, bd))
}
/// The token a method the server serves for the app takes: an access token,
/// and for `getPreferences` a taken-down account's too (`spec/LIFECYCLE.md`).
pub(crate) fn token(s: &Service, nsid: &str, b: Bearer) -> Result<Token, XrpcError> {
match nsid {
"app.bsky.actor.getPreferences" => sessions::takendown_ok_token(s, b),
_ => sessions::access_token(s, b),
}
}
async fn get_preferences(s: Shared, r: Request) -> Result<Resp, XrpcError> {
let t = sessions::access_token(&s, r.bearer())?;
let t = sessions::takendown_ok_token(&s, r.bearer())?;
if proxy::names_other(&s, r.proxy.as_deref()) {
let target = proxy::target(&s, r.proxy.as_deref()).await?;
let got = proxy::forward_query(
crates/pds-server/src/proxy.rs+32−0
@@ -2726,5 +2726,37 @@ mod tests {
.1,
"InvalidRequest"
);
// A taken-down account's is refused where its service token would be made, and sent nowhere.
let admin = format!(
"Basic {}",
base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
format!("admin:{}", crate::testing::ADMIN_PASSWORD)
)
);
let down = json!({ "subject": { "$type": "com.atproto.admin.defs#repoRef", "did": did }, "takedown": { "applied": true } });
crate::testing::call_raw(
&s,
"com.atproto.admin.updateSubjectStatus",
crate::sessions::Bearer::of(Some(&admin)),
&[],
&down.to_string(),
)
.await
.unwrap();
let _ = (notif.take(), appview.take());
for (service, nsid) in [
(&notif.did, "app.bsky.notification.registerPush"),
(&appview.did, "app.bsky.notification.unregisterPush"),
] {
assert_eq!(register(service, nsid).await.1, "AccountTakedown", "{nsid}");
}
let sent: Vec<String> = notif
.take()
.into_iter()
.chain(appview.take())
.map(|g| g.path)
.collect();
assert!(sent.iter().all(|p| !p.starts_with("/xrpc/")), "{sent:?}");
}
}
crates/pds-server/src/scopes.rs+20−0
@@ -268,6 +268,17 @@ pub(crate) struct Grant {
pub scope: Scope,
}
/// Whether the `Authorization` header's first word is the `DPoP` scheme, in any case.
fn dpop_scheme(headers: &HeaderMap) -> bool {
let h = headers
.get(axum::http::header::AUTHORIZATION)
.map(|v| v.as_bytes())
.unwrap_or_default();
h.split(|&b| b == b' ')
.next()
.is_some_and(|w| w.eq_ignore_ascii_case(b"dpop"))
}
/// A call as it arrives over XRPC. For a method that reads a token, a call
/// with the `DPoP` scheme has its token and proof checked, unless it is
/// refused before: for its HTTP method, or a query for its parameters; a
@@ -280,6 +291,15 @@ pub(crate) async fn look(
call: &Call<'_>,
headers: &HeaderMap,
) -> Result<Option<Grant>, Box<Response>> {
// `createAccount` answers a `DPoP` header that is not two words as any
// header of a bad form, before it refuses OAuth credentials and before
// its input.
if matches!(call.bearer, Bearer::Malformed)
&& takes(call.nsid) == Takes::CreateAccount
&& dpop_scheme(headers)
{
return Err(Box::new(respond(crate::invalid_token(), None)));
}
let Bearer::DPoP(token) = call.bearer else {
return Ok(None);
};
harness/checks/lifecycle.mjs+182−21
@@ -13,7 +13,7 @@ import { ADMIN_PASSWORD } from '../lib/env.mjs'
import { checkMail } from '../lib/mail.mjs'
import { begin, end, now } from '../lib/observe.mjs'
import { plcLog } from '../lib/plc.mjs'
import { cand, net, plcUrl, ref, server, wait, waitReady } from '../lib/processes.mjs'
import { cand, net, plcProxy, plcUrl, ref, server, wait, waitReady } from '../lib/processes.mjs'
import { below, chance, pick, rand } from '../lib/random.mjs'
import { count, differ, run } from '../lib/report.mjs'
import { accounts, addAccount, didOf } from '../lib/state.mjs'
@@ -40,6 +40,7 @@ const basic = (user, password) => `Basic ${Buffer.from(`${user}:${password}`).to
const ADMIN = basic('admin', ADMIN_PASSWORD)
const bearer = (t) => `Bearer ${t}`
const repoRef = (did) => ({ $type: `${A}defs#repoRef`, did })
const strongRef = (uri) => ({ $type: `${R}strongRef`, uri, cid: 'bafyreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm' })
const DATETIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/
const APP_PASSWORD = /^[a-z2-7]{4}-[a-z2-7]{4}-[a-z2-7]{4}-[a-z2-7]{4}$/
const TID = /\/[234567a-z]{13}$/
@@ -267,6 +268,20 @@ async function sameOAuth(kind, acct, nsid, request = () => ({})) {
return [a, b]
}
/// The six sync reads of the account's repository with its OAuth session,
/// some or all, compared by status, error and the error of
/// `WWW-Authenticate`: a CAR file or a blob is not compared.
async function oauthSyncReads(acct, tag, some) {
const s = lifeOf(acct).oauth
if (!s) return
for (const [name, nsid, params] of some(SYNC_READS(acct), 3)) {
const [a, b] = await Promise.all(sides().map((side) => sendOAuth(s, side, nsid, { params: params(side) })))
const [na, nb] = [a, b].map((r) => ({ status: r.status, error: r.status >= 400 ? (r.body?.error ?? null) : null, www: wwwError(r.headers?.['www-authenticate']) }))
if (!isDeepStrictEqual(na, nb)) await differ(`${nsid} (${name}, ${tag}, with an OAuth token)`, { params: JSON.parse(strip(ref, JSON.stringify(params(ref)))), auth: 'DPoP <its OAuth access token>' }, na, nb)
count(`lifecycle: ${name}, ${tag}, with an OAuth token`, a.status < 400)
}
}
/// The account's OAuth session refreshed on both sides, compared: refused
/// once the session ended, when it is dropped.
async function refreshOAuth(acct, tag) {
@@ -487,6 +502,9 @@ function syncAuths(acct, other) {
['a wrong Basic', () => basic('admin', 'wrong')],
['a refresh token', (side) => bearer(acct.sides[side.name].refresh)],
['a forged token', () => bearer(FORGED)],
['a DPoP header', () => 'DPoP abc'],
['its token as DPoP', (side) => `DPoP ${acct.sides[side.name].token}`],
['a forged token as DPoP', () => `DPoP ${FORGED}`],
]
if (other) auths.push(['another account\'s token', own(other)])
if (l.reference.td) auths.push(['its takendown session', (side) => bearer(l[side.name].td.access)])
@@ -510,6 +528,8 @@ async function matrix(acct, full) {
await same(`listRecords, ${tag}`, `${R}listRecords`, (side) => ({ params: { repo: did(side), collection: C } }))
if (st.active) await same(`getRecord, ${tag}`, `${R}getRecord`, (side) => ({ params: { repo: did(side), collection: C, rkey: 'a' } }))
for (const [name, nsid, params] of SYNC_READS(acct)) for (const [who, auth] of some(syncAuths(acct, other), 2)) await same(`${name} with ${who}, ${tag}`, nsid, (side) => ({ params: params(side), auth: auth(side) }))
// Of a DID no account has: the token's errors come before RepoNotFound.
for (const [name, nsid, params] of some(SYNC_READS(acct), 2)) for (const [who, auth] of some(syncAuths(acct, other), 2)) await same(`${name} of a DID no account has, with ${who}`, nsid, (side) => ({ params: { ...params(side), did: NOBODY }, auth: auth(side) }))
for (const auth of [undefined, bearer(FORGED)]) await same(`getRepoStatus, ${tag}`, `${Y}getRepoStatus`, (side) => ({ params: { did: did(side) }, auth }))
await checkLatest(acct, st, 'getRepoStatus', async (side) => (await send(side, `${Y}getRepoStatus`, { params: { did: did(side) } })).body?.rev, 'rev')
await same(`listRepos, ${tag}`, `${Y}listRepos`, { params: { limit: 1000 } })
@@ -573,6 +593,7 @@ async function matrix(acct, full) {
await sameOAuth(`getSession, ${tag}`, acct, `${S}getSession`)
await sameOAuth(`checkAccountStatus, ${tag}`, acct, `${S}checkAccountStatus`)
for (const [name, nsid, req] of serviceCalls) await sameOAuth(`${name}, ${tag}`, acct, nsid, req)
await oauthSyncReads(acct, tag, some)
const ok = next()
await sameOAuth(`createRecord, ${tag}`, acct, `${R}createRecord`, (side) => ({ body: { repo: did(side), collection: C, rkey: `o${ok}`, record: { $type: C } } }))
await sameOAuth(`activateAccount, ${tag}`, acct, `${S}activateAccount`, () => ({ method: 'POST' }))
@@ -619,6 +640,39 @@ async function matrix(acct, full) {
await same(`requestAccountDelete with an app password's session, ${tag}`, `${S}requestAccountDelete`, (side) => ({ auth: bearer(l[side.name].priv.access), method: 'POST' }))
await noteMail(acct, `requestAccountDelete, ${tag}`)
}
// The email methods, invite codes, preferences and push registration: a
// taken-down or deleted account is refused after the token, before the
// input (spec/LIFECYCLE.md).
const ownCalls = [
['requestEmailConfirmation', `${S}requestEmailConfirmation`, { method: 'POST' }],
['requestEmailConfirmation with a body', `${S}requestEmailConfirmation`, { body: {} }],
['confirmEmail with a wrong token', `${S}confirmEmail`, { body: { email: acct.email, token: 'AAAAA-BBBBB' } }],
['confirmEmail with bad input', `${S}confirmEmail`, { body: { email: 5 } }],
['requestEmailUpdate', `${S}requestEmailUpdate`, { method: 'POST' }],
['updateEmail with a wrong token', `${S}updateEmail`, { body: { email: acct.email, token: 'AAAAA-BBBBB' } }],
['updateEmail with bad input', `${S}updateEmail`, { body: { email: 5 } }],
['getAccountInviteCodes', `${S}getAccountInviteCodes`, {}],
['getAccountInviteCodes with a bad parameter', `${S}getAccountInviteCodes`, { params: { includeUsed: 'nope' } }],
['getPreferences', 'app.bsky.actor.getPreferences', {}],
['putPreferences', 'app.bsky.actor.putPreferences', { body: { preferences: [] } }],
['putPreferences with bad input', 'app.bsky.actor.putPreferences', { body: { preferences: 5 } }],
]
for (const [name, nsid, req] of some(ownCalls, 6)) await same(`${name}, ${tag}`, nsid, (side) => ({ ...req, auth: own(acct)(side) }))
await same(`getPreferences with an app password's session, ${tag}`, 'app.bsky.actor.getPreferences', (side) => ({ auth: bearer(l[side.name].app.access) }))
await noteMail(acct, `the email methods, ${tag}`)
if (full || chance(0.3)) {
await same(`requestPasswordReset by its email, ${tag}`, `${S}requestPasswordReset`, { body: { email: acct.email } })
await noteMail(acct, `requestPasswordReset, ${tag}`)
}
// Push registration makes a service token, which a taken-down account is
// refused, though the reference makes it (spec/LIFECYCLE.md).
const push = { serviceDid: services.appview.did, token: `push-${acct.n}`, platform: 'web', appId: 'xyz.blueskyweb.app' }
for (const method of ['registerPush', 'unregisterPush']) {
if (!full && chance(0.5)) continue
const request = (side) => ({ auth: own(acct)(side), body: push })
if (st.takendown) await heldAlone(`${method}, ${tag}`, `app.bsky.notification.${method}`, request, { status: 401, error: 'AccountTakedown' })
else await same(`${method}, ${tag}`, `app.bsky.notification.${method}`, request)
}
if (st.deleted) {
await same(`deactivateAccount, ${tag}`, `${S}deactivateAccount`, (side) => ({ auth: own(acct)(side), body: {} }))
await same(`activateAccount, ${tag}`, `${S}activateAccount`, (side) => ({ auth: own(acct)(side), method: 'POST' }))
@@ -702,6 +756,14 @@ async function tdCalls(acct, tag, some) {
['activateAccount', `${S}activateAccount`, { method: 'POST' }],
['requestAccountDelete', `${S}requestAccountDelete`, { method: 'POST' }],
['createAppPassword', `${S}createAppPassword`, { body: { name: `td-${next()}` } }],
['requestEmailConfirmation', `${S}requestEmailConfirmation`, { method: 'POST' }],
['confirmEmail', `${S}confirmEmail`, { body: { email: acct.email, token: 'AAAAA-BBBBB' } }],
['requestEmailUpdate', `${S}requestEmailUpdate`, { method: 'POST' }],
['updateEmail', `${S}updateEmail`, { body: { email: acct.email, token: 'AAAAA-BBBBB' } }],
['getAccountInviteCodes', `${S}getAccountInviteCodes`, {}],
['getPreferences', 'app.bsky.actor.getPreferences', {}],
['putPreferences', 'app.bsky.actor.putPreferences', { body: { preferences: [] } }],
['registerPush', 'app.bsky.notification.registerPush', { body: { serviceDid: services.appview.did, token: `push-${acct.n}`, platform: 'web', appId: 'xyz.blueskyweb.app' } }],
]
for (const [name, nsid, req] of some(calls, 3)) await same(`${name} with a takendown session, ${tag}`, nsid, (side) => ({ ...req, auth: td(side) }))
const key = `t${next()}`
@@ -711,12 +773,16 @@ async function tdCalls(acct, tag, some) {
}
/// The emails sent since the last, compared; a `deleteAccount` one is kept
/// as the account's token on each side.
/// as the account's token on each side, and a `resetPassword` one as its
/// `reset`.
async function noteMail(acct, what) {
const sent = await checkMail(what, { account: `<did:${acct.n}>` })
for (const side of sides()) {
const m = sent[side.name].filter((x) => x.kind === 'deleteAccount' && x.to === acct.email.toLowerCase()).at(-1)
const mine = sent[side.name].filter((x) => x.to === acct.email.toLowerCase())
const m = mine.filter((x) => x.kind === 'deleteAccount').at(-1)
if (m) lifeOf(acct)[side.name].mailed = m.token
const r = mine.filter((x) => x.kind === 'resetPassword').at(-1)
if (r) lifeOf(acct)[side.name].reset = r.token
}
}
@@ -831,6 +897,36 @@ async function adminOdd(acct) {
await getStatus(`getSubjectStatus ${what}`, params)
}
/// Subjects that name no record or account to change: a record's `uri` of a
/// DID alone or a collection alone, a DID no account has, a subject of
/// another `$type` without `takedown`, and `deactivated` of each; then
/// getSubjectStatus of such `uri`s and of one by handle. Each form, every
/// time (spec/LIFECYCLE.md).
async function oddSubjects(acct) {
const did = (side) => didOf(side, acct)
const coin = chance(0.5)
const forms = [
['a record subject of its DID alone', (side) => ({ subject: strongRef(`at://${did(side)}`), takedown: { applied: coin } })],
['a record subject of a collection alone', (side) => ({ subject: strongRef(`at://${did(side)}/${C}`), takedown: { applied: coin } })],
['a record subject of its DID alone, deactivating', (side) => ({ subject: strongRef(`at://${did(side)}`), deactivated: { applied: coin } })],
['a record subject of a DID no account has alone', () => ({ subject: strongRef(`at://${NOBODY}`), takedown: { applied: coin } })],
['a record of a DID no account has, deactivating', () => ({ subject: strongRef(`at://${NOBODY}/${C}/t`), deactivated: { applied: coin } })],
['a blob of a DID no account has, deactivating', () => ({ subject: { $type: `${A}defs#repoBlobRef`, did: NOBODY, cid: lifeOf(acct).blob }, deactivated: { applied: coin } })],
['a subject of another type, deactivating', (side) => ({ subject: { $type: 'com.example.subject', did: did(side) }, deactivated: { applied: coin } })],
['a subject of another type, neither attribute', (side) => ({ subject: { $type: 'com.example.subject', did: did(side) } })],
['a subject of another type, a lifted takedown and deactivating', (side) => ({ subject: { $type: 'com.example.subject', did: did(side) }, takedown: { applied: false }, deactivated: { applied: coin } })],
]
for (const [how, body] of forms) await updateStatus(`updateSubjectStatus with ${how}`, body)
const gets = [
['of its DID alone as a uri', (side) => ({ uri: `at://${did(side)}` })],
['of a collection alone', (side) => ({ uri: `at://${did(side)}/${C}` })],
['of a record by handle', () => ({ uri: `at://${acct.handle}/${C}/a` })],
['of a record by a handle no account has', () => ({ uri: `at://nobody-${next()}.test/${C}/a` })],
]
for (const [what, params] of gets) await getStatus(`getSubjectStatus ${what}`, params)
await getStatus('getSubjectStatus of an account', (side) => ({ did: did(side) }))
}
/// The admin methods with auth that is not the admin's.
async function adminAuth(acct) {
const l = lifeOf(acct)
@@ -962,6 +1058,12 @@ async function deletion(acct) {
await same('requestAccountDelete', `${S}requestAccountDelete`, (side) => ({ auth: own(acct)(side), method: 'POST' }))
await noteMail(acct, 'requestAccountDelete')
}
// A password reset asked for before the deletion: its token is gone with
// the account.
if (chance(0.5)) {
await same('requestPasswordReset before a deletion', `${S}requestPasswordReset`, { body: { email: acct.email } })
await noteMail(acct, 'requestPasswordReset before a deletion')
}
if (!l.reference.mailed || !l.server.mailed) return
if (chance(0.4)) {
const old = { reference: l.reference.mailed, server: l.server.mailed }
@@ -988,6 +1090,16 @@ async function deletion(acct) {
await matrix(acct, true)
await checkEvents(`what a deleted account answers`)
await checkReplay('deleteAccount')
// Its activation: the body first, then its DID document as validDid reads
// it, and only then its key, which is gone (spec/LIFECYCLE.md).
await same('activateAccount with a body, deleted', `${S}activateAccount`, (side) => ({ auth: own(acct)(side), body: {} }))
if (chance(0.5)) {
await moveDid(acct, () => 'https://elsewhere.example.com')
await same('activateAccount of a deleted account with its DID elsewhere', `${S}activateAccount`, (side) => ({ auth: own(acct)(side), method: 'POST' }))
await updateStatus('updateSubjectStatus activating a deleted account with its DID elsewhere', (side) => ({ subject: repoRef(did(side)), deactivated: { applied: false } }))
await moveDid(acct, (side) => side.publicUrl)
}
if (l.reference.reset && l.server.reset) await same('resetPassword with a token mailed before the deletion', `${S}resetPassword`, (side) => ({ body: { token: l[side.name].reset, password: 'a-new-password' } }))
// Its handle and email are free.
if (chance(0.25)) {
const [a, b] = await same('updateHandle to a deleted account\'s handle', `${I}updateHandle`, (side) => ({ auth: own(other)(side), body: { handle: acct.handle } }))
@@ -1016,25 +1128,29 @@ async function sameHandleAccount(gone) {
await prepare(acct)
}
/// The account's DID moved to another server by an operation each side
/// signs with its rotation key, then back: checkAccountStatus's `validDid`,
/// and activation refused while it is away.
/// The account's DID moved by an operation each side signs with its
/// rotation key, its `atproto_pds` endpoint `to` (a function of the side).
async function moveDid(acct, to) {
for (const side of sides()) {
const did = didOf(side, acct)
const last = (await plcLog(did)).body.at(-1)
const { sig: _, ...fields } = last
const op = { ...fields, services: { ...fields.services, atproto_pds: { type: 'AtprotoPersonalDataServer', endpoint: to(side) } }, prev: (await cidForCbor(last)).toString() }
const signed = { ...op, sig: Buffer.from(await side.plcSigner.sign(cborEncode(op))).toString('base64url') }
const r = await fetch(`${plcUrl}/${did}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(signed) })
if (!r.ok) await differ('an operation of the harness\'s own', { did: `<did:${acct.n}>` }, 'the directory takes it', { status: r.status, body: await r.text() }, 'the harness fails its own step')
}
await net.pds.ctx.idResolver.did.resolve(didOf(ref, acct), true)
}
/// The account's DID moved to another server, then back:
/// checkAccountStatus's `validDid`, and activation refused while it is
/// away. Or, now and then, the PLC directory down for both sides instead.
async function validDid(acct) {
const st = await stateOf(acct)
if (st.deleted) return
const move = async (to) => {
for (const side of sides()) {
const did = didOf(side, acct)
const last = (await plcLog(did)).body.at(-1)
const { sig: _, ...fields } = last
const op = { ...fields, services: { ...fields.services, atproto_pds: { type: 'AtprotoPersonalDataServer', endpoint: to(side) } }, prev: (await cidForCbor(last)).toString() }
const signed = { ...op, sig: Buffer.from(await side.plcSigner.sign(cborEncode(op))).toString('base64url') }
const r = await fetch(`${plcUrl}/${did}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(signed) })
if (!r.ok) await differ('an operation of the harness\'s own', { did: `<did:${acct.n}>` }, 'the directory takes it', { status: r.status, body: await r.text() }, 'the harness fails its own step')
}
await net.pds.ctx.idResolver.did.resolve(didOf(ref, acct), true)
}
await move(() => 'https://elsewhere.example.com')
if (chance(0.4)) return directoryDown(acct, st)
await moveDid(acct, () => 'https://elsewhere.example.com')
await same('checkAccountStatus with its DID elsewhere', `${S}checkAccountStatus`, (side) => ({ auth: own(acct)(side) }))
await same('deactivateAccount with its DID elsewhere', `${S}deactivateAccount`, (side) => ({ auth: own(acct)(side), body: {} }))
await same('activateAccount with its DID elsewhere', `${S}activateAccount`, (side) => ({ auth: own(acct)(side), method: 'POST' }))
@@ -1044,11 +1160,56 @@ async function validDid(acct) {
await updateStatus(`updateSubjectStatus activating${both ? ' and lifting a takedown' : ''} with its DID elsewhere`, (side) => ({ subject: repoRef(didOf(side, acct)), ...(both ? { takedown: { applied: false } } : {}), deactivated: { applied: false } }))
await getStatus('getSubjectStatus with its DID elsewhere', (side) => ({ did: didOf(side, acct) }))
await checkEvents('activation with its DID elsewhere')
await move((side) => side.publicUrl)
await moveDid(acct, (side) => side.publicUrl)
await same('checkAccountStatus with its DID back', `${S}checkAccountStatus`, (side) => ({ auth: own(acct)(side) }))
if (!st.deactivated) await same('activateAccount with its DID back', `${S}activateAccount`, (side) => ({ auth: own(acct)(side), method: 'POST' }))
}
/// The PLC directory down for both sides, closing each connection or
/// answering `500`: the server's requests to it go through the harness's
/// proxy, and the reference's PLC client is pointed at the proxy while it
/// is down. `validDid` is then `false`, and an activation `502
/// UpstreamFailure`, a takedown lifted in the same call staying lifted
/// (spec/LIFECYCLE.md).
async function directoryDown(acct, st) {
const mode = pick(['refuse', 'error'])
const how = mode === 'refuse' ? 'unreachable' : 'failing'
const client = net.pds.ctx.plcClient
const was = client.url
client.url = plcProxy.url
plcProxy.down = mode
try {
await same(`checkAccountStatus with the directory ${how}`, `${S}checkAccountStatus`, (side) => ({ auth: own(acct)(side) }))
if (chance(0.3)) await same(`deactivateAccount with the directory ${how}`, `${S}deactivateAccount`, (side) => ({ auth: own(acct)(side), body: {} }))
await same(`activateAccount with the directory ${how}`, `${S}activateAccount`, (side) => ({ auth: own(acct)(side), method: 'POST' }))
const both = st.takendown && chance(0.5)
await updateStatus(`updateSubjectStatus activating${both ? ' and lifting a takedown' : ''} with the directory ${how}`, (side) => ({ subject: repoRef(didOf(side, acct)), ...(both ? { takedown: { applied: false } } : {}), deactivated: { applied: false } }))
if (chance(0.3)) await updateStatus(`updateSubjectStatus activating a DID no account has with the directory ${how}`, () => ({ subject: repoRef(NOBODY), deactivated: { applied: false } }))
} finally {
plcProxy.down = null
client.url = was
}
await getStatus(`getSubjectStatus after the directory was ${how}`, (side) => ({ did: didOf(side, acct) }))
}
/// A password reset of the account, in whatever state it is, with its own
/// password again: the server ends its OAuth sessions and signs it out of
/// its devices where the reference does not (spec/EMAIL.md), so both sides'
/// are dropped after: its OAuth session, its device for silent sign-in, and
/// the browsers checks/oauth.mjs signs it in with.
async function passwordReset(acct) {
const l = lifeOf(acct)
for (const side of sides()) l[side.name].reset = null
await same('requestPasswordReset', `${S}requestPasswordReset`, { body: { email: acct.email } })
await noteMail(acct, 'requestPasswordReset')
if (!l.reference.reset || !l.server.reset) return
await same('resetPassword', `${S}resetPassword`, (side) => ({ body: { token: l[side.name].reset, password: acct.password } }))
for (const side of sides()) l[side.name].reset = null
l.oauth = null
l.device = null
acct.oauth = undefined
}
/// A takendown session made, its tokens checked and used.
async function takendownLogin(acct) {
const st = await stateOf(acct)
@@ -1110,7 +1271,7 @@ async function crash() {
const CHANGES = [
[deactivate, 8], [activate, 8], [takedown, 5], [lift, 5], [adminDeactivation, 4], [adminOdd, 4], [adminAuth, 2],
[recordTakedown, 5], [blobTakedown, 5], [deleteErrors, 3], [deletion, 4], [validDid, 2], [takendownLogin, 3],
[recordTakedown, 5], [blobTakedown, 5], [deleteErrors, 3], [deletion, 4], [validDid, 3], [takendownLogin, 3], [passwordReset, 2], [oddSubjects, 2],
]
/// The changes a request approved before may be exchanged after: those
/// whose ending of it the harness knows (spec/LIFECYCLE.md, "OAuth
harness/checks/oauth-scopes.mjs+47−1
harness/lib/plc-proxy.mjs+12−5
harness/lib/processes.mjs+5−5
harness/compare.mjs+2−2
spec/EMAIL.md+3−1
spec/LIFECYCLE.md+129−52
spec/LIMITS.md+3−1
spec/OAUTH-SCOPES.md+24−5
spec/PROXY.md+5−2