Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ review bots read and write at the same time, written in Rust.
- `tools/xtask`: development tasks, run with `cargo xtask`, such as timing
origin against git (`just bench-git`).

## API changes

Every server feature lives in `OriginService`; transports like HTTP only
translate requests. A new HTTP endpoint also takes a line in the SDK's
`endpoints!` macro, and `just openapi` to update `docs/openapi.json`.

## Testing & Benchmarks

Performance is a primary goal, so benchmarks matter as much as tests. A change
Expand Down
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ origin remote [<url>] # show or set the remote: http://host:port/<
origin push [<change>...] # share changes and the ones below them; lands nothing
origin fetch [--target <t>] [--change <id>] # new acceptances, and the records of known changes
origin pull # fetch, then move the working copy onto its target's tip
origin whoami | permissions # who the remote thinks you are, and what you may do there
origin token issue --scope "write src" [--ttl 1h] # a short-lived token for an agent
```

Landing rebases a change onto the target's tip, file by file, checks the
Expand Down Expand Up @@ -115,6 +117,14 @@ send each server under `[tokens]`, by its URL
(`"http://127.0.0.1:7878" = "<token>"`), or in `$ORIGIN_TOKEN`. See
[the design](docs/design.md) for the model.

`origin token issue --scope <capability>... --ttl <period>` asks the remote
for a token acting for you with a narrower scope, such as `write src`,
`read /`, `annotate ci.*`, `land main` or `admin`; the server verifies it
without storing it. A server's operator signs one for any principal with
`origin token issue --config origin-server.toml --as user:agent-1 --scope
...`. A token never grants more than its principal's rights, lasts at most
7 days, and a token issued with a token expires with it.

`converge` merges the files of a change's heads. A text file two heads
changed holds both versions between conflict markers (`<<<<<<<`, `=======`,
`>>>>>>>`), and a binary one keeps one side. A `core.conflict` statement
Expand Down
59 changes: 57 additions & 2 deletions apps/origin-src/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ use std::str::FromStr;
use anyhow::{Context, Result};
use clap::error::ErrorKind;
use clap::{Args, CommandFactory, Parser, Subcommand};
use origin_shared::access::Capability;
use origin_shared::policy::KindPattern;
use origin_shared::{ChangeId, Digest, Inputs, Kind, RepoPath, TargetName, Verdict};
use origin_shared::{
ChangeId, Digest, Inputs, Kind, Period, Principal, RepoPath, TargetName, Verdict,
};

use crate::config::UserConfig;
use crate::oplog::Actor;
Expand Down Expand Up @@ -54,6 +57,9 @@ enum Command {
/// Manage the repositories a server hosts.
#[command(subcommand)]
Repo(RepoCommand),
/// Manage tokens.
#[command(subcommand)]
Token(TokenCommand),
#[command(flatten)]
Workspace(WorkspaceCommand),
}
Expand All @@ -71,6 +77,29 @@ enum RepoCommand {
},
}

#[derive(Debug, Subcommand)]
enum TokenCommand {
/// Issue a short-lived token with a narrower scope, for an agent or a
/// CI runner: the remote signs one acting for you, or, with
/// `--config`, a server signs one for anyone.
Issue {
/// A capability: `read <path>`, `write <path>`, `annotate <kind>`,
/// `land <target>`, `land *` or `admin`. Repeat it for several.
#[arg(long, required = true)]
scope: Vec<Capability>,
/// How long it lasts, such as `1h` or `7d`, the most a token lasts.
#[arg(long, default_value = "1h")]
ttl: Period,
/// Sign it with the key of the server this configuration file
/// describes, instead of asking the remote.
#[arg(short, long, requires = "principal")]
config: Option<PathBuf>,
/// Who it acts for, with `--config`, such as `user:agent-1`.
#[arg(long = "as", requires = "config")]
principal: Option<Principal>,
},
}

/// Commands run in the repository containing the current directory. Those
/// that read the working copy snapshot it first. Changes are named by a
/// unique prefix of their id, or `@` for the working copy's.
Expand Down Expand Up @@ -206,6 +235,11 @@ enum WorkspaceCommand {
/// change went, or onto its target's new tip, with the edits made
/// since.
Pull,
/// Show who the remote thinks you are.
Whoami,
/// Show what the remote lets you do: the paths you read and write, the
/// statements you issue, and the targets you land on.
Permissions,
/// Share changes with the remote, with the changes below them: their
/// revisions, files and statements. Lands nothing.
Push {
Expand Down Expand Up @@ -487,7 +521,22 @@ impl Cli {
Command::Repo(RepoCommand::Create { path, config }) => {
return ServerConfig::load(&config)?.create_repo(&path);
}
Command::Init { .. } | Command::Clone { .. } | Command::Workspace(_) => {}
Command::Token(TokenCommand::Issue {
scope,
ttl,
config: Some(config),
principal: Some(principal),
}) => {
println!(
"{}",
ServerConfig::load(&config)?.issue_token(principal, scope, ttl.0)?
);
return Ok(());
}
Command::Init { .. }
| Command::Clone { .. }
| Command::Token(_)
| Command::Workspace(_) => {}
}
let config = UserConfig::load()?;
// The op log records the command line, without the program's name,
Expand All @@ -506,6 +555,10 @@ impl Cli {
Workspace::clone(&url, path.as_deref(), &target, config, &actor)?;
}
Command::Workspace(command) => command.run(config, &actor)?,
Command::Token(TokenCommand::Issue { scope, ttl, .. }) => {
let cwd = env::current_dir().context("cannot read the current directory")?;
Workspace::discover(&cwd, config, &actor)?.issue_token(scope, ttl)?;
}
Command::Serve { .. } | Command::Repo(_) => unreachable!("run above"),
}
Ok(())
Expand Down Expand Up @@ -564,6 +617,8 @@ impl WorkspaceCommand {
Self::Remote { url } => workspace.set_remote(url.as_deref())?,
Self::Fetch { target, change } => workspace.fetch(&target, &change)?,
Self::Pull => workspace.pull()?,
Self::Whoami => workspace.whoami()?,
Self::Permissions => workspace.permissions()?,
Self::Push { changes } => workspace.push(&changes)?,
Self::Watch {
kind,
Expand Down
58 changes: 55 additions & 3 deletions apps/origin-src/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use origin_shared::ChangeId;
use origin_shared::Head;
use origin_shared::access::InvalidToken;
use origin_shared::access::{InvalidToken, Rights};
use origin_shared::api::{
Annotation, ApiError, ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, Inventory,
InventoryRequest, LandRequest, Landings, LogEntry, LogQuery, MORE, NewTarget, PutQuery,
RepoName, RepoSummary, Revisions, StatementsQuery, Stored, TargetInfo,
InventoryRequest, IssuedToken, LandRequest, Landings, LogEntry, LogQuery, MORE, NewTarget,
PutQuery, RepoName, RepoSummary, Revisions, StatementsQuery, Stored, TargetInfo, TokenRequest,
};
use origin_shared::event::Page;
use origin_shared::landing::Pending;
Expand Down Expand Up @@ -68,6 +68,8 @@ impl Api {
.routes(routes!(land))
.routes(routes!(landings))
.routes(routes!(events))
.routes(routes!(whoami))
.routes(routes!(issue_token))
.routes(routes!(openapi_document))
}

Expand Down Expand Up @@ -152,6 +154,7 @@ impl IntoResponse for HttpError {
ErrorCode::Conflict => StatusCode::CONFLICT,
ErrorCode::Expired => StatusCode::GONE,
ErrorCode::Unauthorized => StatusCode::UNAUTHORIZED,
ErrorCode::Forbidden => StatusCode::FORBIDDEN,
ErrorCode::Internal => StatusCode::INTERNAL_SERVER_ERROR,
};
(status, Json(ApiError { code, message })).into_response()
Expand Down Expand Up @@ -515,6 +518,55 @@ async fn events(
.map(Json)
}

/// Tells the caller who they are and what they may do in the repository.
#[utoipa::path(
get,
path = "/api/v1/repos/{repo}/whoami",
operation_id = "whoami",
params(("repo" = String, Path, description = "The repository")),
responses(
(status = 200, description = "The caller's rights", body = Rights),
(status = 401, description = "The token is invalid or expired", body = ApiError),
(status = 404, description = "The repository does not exist", body = ApiError)
)
)]
async fn whoami(
repos: Repos,
Path(repo): Path<RepoName>,
caller: Caller,
) -> Result<Json<Rights>, HttpError> {
call(repos, repo, caller, OriginService::whoami)
.await
.map(Json)
}

/// Issues a token acting for the caller, with a scope narrowing their
/// rights, signed by the server, which verifies it without storing it.
#[utoipa::path(
post,
path = "/api/v1/repos/{repo}/tokens",
operation_id = "issue_token",
params(("repo" = String, Path, description = "The repository whose policy the scope is checked against")),
request_body = TokenRequest,
responses(
(status = 200, description = "The token", body = IssuedToken),
(status = 403, description = "The caller isn't signed in, or the scope reaches beyond their rights", body = ApiError),
(status = 404, description = "The repository does not exist", body = ApiError)
)
)]
async fn issue_token(
repos: Repos,
Path(repo): Path<RepoName>,
caller: Caller,
Json(request): Json<TokenRequest>,
) -> Result<Json<IssuedToken>, HttpError> {
call(repos, repo, caller, move |service, caller| {
service.issue_token(caller, &request)
})
.await
.map(Json)
}

/// The OpenAPI document of this API.
#[utoipa::path(
get,
Expand Down
11 changes: 11 additions & 0 deletions apps/origin-src/src/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,14 @@ impl Caller {
}
}
}

/// Something a caller may not do.
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub enum Forbidden {
/// The owner has no principal to issue a token for.
#[error("only a signed-in caller gets a token, for themselves")]
NoPrincipal,
/// A token's scope reaches beyond its issuer's rights.
#[error("a token may only narrow your rights, which don't include `{0}`")]
Scope(Capability),
}
11 changes: 9 additions & 2 deletions apps/origin-src/src/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ use std::path::{self, Path, PathBuf};

use origin_client::Client;
use origin_shared::Head;
use origin_shared::access::Rights;
use origin_shared::api::{
ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, Inventory, InventoryRequest, LandRequest,
Landings, LogEntry, LogQuery, NewTarget, PutQuery, RepoName, Stored, TargetInfo,
ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, Inventory, InventoryRequest, IssuedToken,
LandRequest, Landings, LogEntry, LogQuery, NewTarget, PutQuery, RepoName, Stored, TargetInfo,
TokenRequest,
};
use origin_shared::event::Page;
use origin_shared::landing::Pending;
Expand Down Expand Up @@ -92,6 +94,11 @@ calls! {
fn create_target(request: &NewTarget) -> Head = create_target(request), create_target(request);
/// The events after a cursor, waiting for some.
fn events(query: &EventsQuery) -> Page = events(query), events(query);
/// Who the remote thinks the user is, and what they may do there.
fn whoami() -> Rights = whoami(), whoami();
/// Issues a token acting for the user, with a narrower scope.
fn issue_token(request: &TokenRequest) -> IssuedToken =
issue_token(request), issue_token(request);
}

impl Remote {
Expand Down
49 changes: 47 additions & 2 deletions apps/origin-src/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ use std::thread;
use std::time::Duration;

use anyhow::Context;
use origin_shared::PrincipalName;
use origin_shared::access::{Capability, Token};
use origin_shared::api::{RepoName, RepoSummary};
use origin_shared::{Principal, PrincipalName};
use serde::Deserialize;

use crate::auth::{Credentials, StaticTokens};
Expand All @@ -40,7 +41,8 @@ use crate::store::Store;
/// ```
///
/// Paths are relative to the file. Callers without a token are anonymous;
/// the server also takes the scoped tokens it signed.
/// the server also takes the scoped tokens it signed (see
/// [`ServerConfig::issue_token`]).
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ServerConfig {
Expand Down Expand Up @@ -119,6 +121,26 @@ impl ServerConfig {
Ok(())
}

/// `origin token issue --config <file> --as <principal>`: signs a
/// token acting for `principal` with `scope`, valid for `ttl`, at most
/// [`OriginService::MAX_TOKEN_TTL`] as any token, with the server's key,
/// and returns it. The token acts with the principal's rights in each
/// repository, narrowed to the scope, so an operator can hand agents
/// identities of their own.
///
/// # Errors
///
/// Fails if the key cannot be read or generated.
pub fn issue_token(
&self,
principal: Principal,
scope: Vec<Capability>,
ttl: Duration,
) -> anyhow::Result<String> {
let ttl = ttl.min(OriginService::MAX_TOKEN_TTL);
Ok(Token::new(principal, scope, ttl).sign(&self.node()?.key))
}

/// `origin serve`: serves the repositories until interrupted, logging
/// failures to stderr. Prints the address it listens on, which tells
/// callers that chose port 0 where to connect.
Expand Down Expand Up @@ -267,3 +289,26 @@ impl Repositories {
.ok_or_else(|| ServiceError::UnknownRepository(name.clone()))
}
}

#[cfg(test)]
mod tests {
use std::time::{SystemTime, UNIX_EPOCH};

use super::*;

#[test]
fn tokens_signed_with_the_key_last_at_most_a_week() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("origin-server.toml");
fs::write(&path, "listen = \"127.0.0.1:0\"\nnode = \"hosted\"\n").unwrap();
let config = ServerConfig::load(&path).unwrap();
let month = Duration::from_hours(30 * 24);
let text = config
.issue_token("user:agent".parse().unwrap(), Vec::new(), month)
.unwrap();
let token = Token::verify(&text, &config.node().unwrap().key.public()).unwrap();
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let cap = (now + OriginService::MAX_TOKEN_TTL).as_secs();
assert!(token.expires <= cap && token.expires + 60 > cap);
}
}
Loading