Skip to main content

stratum_node_core/
lib.rs

1//! Zero-I/O core types for Stratum pod nodes.
2//!
3//! **Pre-release:** this is `0.1.0-alpha`. The API and formats may change
4//! before 0.1.0.
5//!
6//! A Stratum node is administered by a Nostr key. This crate holds the parts
7//! of that model that need no I/O, so the controller, the command-line client
8//! and any other implementation agree byte for byte:
9//!
10//! - **Principals.** [`DidNostr`] is a `did:nostr` identifier over a BIP-340
11//!   x-only public key, convertible to and from hex and NIP-19 `npub`.
12//! - **Identifiers.** [`EventId`], [`Sha256Digest`], [`ChallengeId`],
13//!   [`InvitationId`], [`OperationId`], [`Revision`] and [`UnixTime`] each
14//!   have one canonical
15//!   text form and validate on construction and deserialisation.
16//! - **Events.** [`SignedEvent`] is a NIP-01 event whose ID and signature
17//!   have been verified; [`UnsignedEvent`] is one waiting to be signed by a
18//!   [`NostrSecretKey`].
19//! - **Signed requests.** [`verify_request`] checks an `Authorization: Nostr`
20//!   header against the request the server received, under a profile
21//!   stricter than NIP-98, and returns a [`VerifiedRequest`].
22//!   [`NostrSecretKey::sign_request`] produces such headers, and
23//!   [`NostrSecretKey::sign_request_with_nonce`] adds a random `nonce` tag
24//!   so identical requests signed in one second are distinct events.
25//!   [`verify_request_without_body`] checks everything but the body digest,
26//!   for a proxy that never sees the body, and returns a
27//!   [`BodyUncheckedRequest`]. [`UnverifiedRequest`] parses a header once so
28//!   its claimed author can be looked up before a signature is verified.
29//! - **Bootstrap claims.** [`ClaimBody`] is the immutable body an
30//!   administrator signs to claim a node, kept as the exact bytes issued.
31//! - **Pod paths.** [`PodPath`] is a request path under the pod allow-list
32//!   (`/pods/<pk>/…` or `/pods/<pk>.acl`) and its shape rules, with the
33//!   owner, container and sibling-ACL helpers a client needs;
34//!   [`is_valid_pod_query`] checks a query string.
35//! - **Admission.** [`AdmissionClaim`] is the body a tenant signs to redeem
36//!   an invitation ([`InvitationId`]) after reading
37//!   [`ADMISSION_NOTICE_V1`]; [`MemberState`] names the states a membership
38//!   moves through, with one predicate each for capacity, provisioning and
39//!   the gate's directory. [`DirectoryMemberState`] is the gate's tolerant
40//!   reading of a directory entry, which keeps an unknown state as a
41//!   refused member instead of failing the whole document.
42//! - **Member administration.** [`MemberActionRequest`], [`RemoveRequest`],
43//!   [`SuspendResponse`], [`ResumeResponse`], [`ArchiveResponse`],
44//!   [`RemoveResponse`] and [`MemberView`] are the bodies of the
45//!   administrator's suspend, resume, archive, remove and member-view
46//!   routes; [`Enforcement`] reports whether the gate applies a suspension,
47//!   and [`RemovalArchive`] is an archive reference or a waiver.
48//!   [`ErrorCode`] defines the codes Steps 3a and 3b add, from
49//!   `suspended` to `lease_expired`.
50//! - **Applications and installations (Step 3b).** [`ValidManifest`]
51//!   validates an application [`Manifest`] against the node's
52//!   [`JobCeilings`], naming the member and [`ManifestRule`] of a refusal;
53//!   [`ImageId`], [`ContainerPath`], [`MilliCpus`] and [`JobLimits`] are its
54//!   parts. [`render_offered`] renders the [`OfferedGrant`], the WAC
55//!   authorisations a member consents to, byte for byte as the controller
56//!   stores them. [`Schedule`] does the period arithmetic. The tenant and
57//!   administrator route bodies, the identifiers ([`ApplicationId`],
58//!   [`InstallationId`], [`JobId`]), the states and the
59//!   [`EnforcementParts`] of a withdrawal or suspension are in the same
60//!   group, and [`DirectoryAppKey`] is the gate directory's `app_keys`
61//!   entry.
62//! - **Profile document.** [`profile_card_path`] and [`profile_owner`] give
63//!   the one public path per pod and the gate's byte-exact matcher for it;
64//!   [`profile_card`] and [`profile_acl`] are the document and ACL a client
65//!   writes, and [`card_names_owner`] is `profile init`'s conservative
66//!   check of an existing card.
67//!
68//! The crate never reads a clock, a random source, the environment, the
69//! filesystem or the network. The current time, auxiliary signing
70//! randomness, challenge bytes and the expected request are all parameters,
71//! which keeps every check deterministic and testable.
72//!
73//! Cryptography comes from maintained crates: BIP-340 Schnorr from `k256`,
74//! SHA-256 from `sha2`, bech32 from `bech32`. The signing and verification
75//! paths are tested against the published BIP-340 vectors.
76//!
77//! # Replay protection
78//!
79//! [`verify_request`] proves who signed a request, for which URL, method and
80//! body, and roughly when. It does not make a request single use. A server
81//! must record [`VerifiedRequest::event_id`] durably and refuse a repeat.
82//!
83//! # Example
84//!
85//! ```
86//! use stratum_node_core::{verify_request, ExpectedRequest, NostrSecretKey, RequestPolicy, UnixTime};
87//!
88//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
89//! // Client side: sign a request. Use real randomness for the 32 bytes.
90//! let key = NostrSecretKey::from_nsec(
91//!     "nsec1vl029mgpspedva04g90vltkh6fvh240zqtv9k0t9af8935ke9laqsnlfe5",
92//! )?;
93//! let body = br#"{"node":"did:nostr:...","operation_id":"op-1"}"#;
94//! let request = ExpectedRequest::new("POST", "http://127.0.0.1:7070/api/v1/config/apply", Some(body));
95//! let now = UnixTime::from_secs(1_764_720_000);
96//! let header = key.sign_request(&request, now, &[0x42; 32])?;
97//!
98//! // Server side: verify it against what actually arrived.
99//! let verified = verify_request(&header, &request, now, &RequestPolicy::new())?;
100//! assert_eq!(verified.signer(), key.public());
101//! # Ok(())
102//! # }
103//! ```
104
105mod admission;
106mod claim;
107mod did;
108mod directory;
109mod encoding;
110mod error_code;
111mod event;
112mod grant;
113mod id;
114mod installations;
115mod manifest;
116mod members;
117mod pod_path;
118mod profile;
119mod request;
120mod schedule;
121mod schnorr;
122mod secret;
123
124pub use admission::{
125    admission_notice_v1_sha256, AdmissionClaim, AdmissionFields, CheckAdmissionError,
126    DirectoryMemberState, MemberState, ParseAdmissionError, ParseMemberStateError,
127    ADMISSION_CLAIM_PURPOSE, ADMISSION_NOTICE_V1,
128};
129pub use claim::{CheckClaimError, ClaimBody, ClaimFields, ParseClaimError, CLAIM_BODY_VERSION};
130pub use did::{DidNostr, ParseDidError};
131pub use directory::DirectoryAppKey;
132pub use error_code::ErrorCode;
133pub use event::{ParseEventError, SignedEvent, UnsignedEvent};
134pub use grant::{render_container, render_offered, OfferedContainer, OfferedGrant};
135pub use id::{
136    ChallengeId, EventId, InvitationId, OperationId, ParseIdError, Revision, Sha256Digest,
137    UnixTime, OPERATION_ID_MAX_LEN,
138};
139pub use installations::{
140    ApplicationActionRequest, ApplicationId, ApplicationList, ApplicationState,
141    ApplicationStateResponse, ApplicationView, ApproveApplicationRequest,
142    ApproveApplicationResponse, Catalogue, CatalogueEntry, CleanupRequest, CleanupResponse,
143    ConsentRequest, ConsentResponse, CreateInstallationRequest, CreateInstallationResponse,
144    EnforcementParts, GrantState, InstallationActionRequest, InstallationId, InstallationList,
145    InstallationState, InstallationView, JobCounts, JobId, JobList, JobOutcome, JobState, JobView,
146    KeyReason, KeyStatus, KeysPart, LeaseState, ResumeInstallationResponse, RunRequest,
147    RunResponse, WithdrawResponse, WorkPart, WorkspaceGrant, WorkspaceSlotState, WorkspaceView,
148};
149pub use manifest::{
150    AclMode, ContainerGrant, ContainerPath, ContainerPathError, ImageId, JobCeilings, JobLimits,
151    Manifest, ManifestError, ManifestLimits, ManifestProfile, ManifestRule, MilliCpus,
152    ParseImageIdError, ParseNameError, PodMethod, ValidManifest, WorkspaceMode, MAX_CONTAINERS,
153    MAX_LABEL_CHARS, MEMORY_STEP_BYTES, MIN_MEMORY_BYTES, MIN_TIMEOUT_SECS,
154};
155pub use members::{
156    ArchiveResponse, Enforcement, MemberActionRequest, MemberView, ParseRemovalArchiveError,
157    RemovalArchive, RemoveRequest, RemoveResponse, ResumeResponse, SuspendResponse,
158};
159pub use pod_path::{is_acl_path, is_valid_pod_query, ParsePodPathError, PodPath};
160pub use profile::{
161    card_names_owner, profile_acl, profile_card, profile_card_path, profile_owner,
162    PROFILE_CARD_RELATIVE, PROFILE_CONTENT_TYPE, PROFILE_MAX_BYTES,
163};
164pub use request::{
165    verify_request, verify_request_without_body, BodyUncheckedRequest, ExpectedRequest,
166    RequestPolicy, RequestPolicyError, RequestTarget, UnverifiedRequest, VerifiedRequest,
167    VerifyRequestError, HTTP_AUTH_KIND,
168};
169pub use schedule::{
170    check_schedule_secs, EndedPeriods, Schedule, ScheduleError, MAX_SCHEDULE_SECS,
171    MIN_SCHEDULE_SECS,
172};
173pub use secret::{NostrSecretKey, ParseKeyError, SignError};
174
175/// The version of the signed-request profile [`verify_request`] enforces and
176/// [`NostrSecretKey::sign_request`] and
177/// [`NostrSecretKey::sign_request_with_nonce`] produce. The `nonce` tag is
178/// outside the profile, which ignores tags it does not name.
179pub const REQUEST_PROFILE_VERSION: u32 = 1;
180
181/// Compiles and runs the README example as a doctest.
182#[cfg(doctest)]
183#[doc = include_str!("../README.md")]
184struct ReadmeDoctests;