use crate::credential::{CheckFuture, CredentialCheck, CredentialVerifier};
use std::future::Future;
use std::pin::Pin;
pub const CALLBACK_PATH: &str = "/callback";
pub const PENDING_TTL_SECS: u64 = 600;
pub const MAX_UPSTREAM_CREDENTIAL_LEN: usize = 2048;
pub const MAX_SUBJECT_CHARS: usize = 200;
#[derive(Clone)]
#[non_exhaustive]
pub struct UpstreamGrant {
pub credential: String,
pub subject: Option<String>,
}
impl UpstreamGrant {
pub fn new(credential: impl Into<String>) -> Self {
UpstreamGrant {
credential: credential.into(),
subject: None,
}
}
pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
self.subject = Some(subject.into());
self
}
}
impl std::fmt::Debug for UpstreamGrant {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UpstreamGrant")
.field("credential", &"[redacted]")
.field("subject", &self.subject)
.finish()
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum Exchange {
Granted(UpstreamGrant),
Refused(String),
Unavailable(String),
}
pub type ExchangeFuture<'a> = Pin<Box<dyn Future<Output = Exchange> + Send + 'a>>;
pub trait UpstreamSignIn: Send + Sync + 'static {
fn provider(&self) -> &str;
fn authorize_url(&self, redirect_uri: &str, state: &str) -> String;
fn exchange<'a>(&'a self, code: &'a str, redirect_uri: &'a str) -> ExchangeFuture<'a>;
}
pub struct UpstreamVerifier<U> {
label: String,
help: String,
generation: Vec<u8>,
upstream: U,
}
impl<U: UpstreamSignIn> UpstreamVerifier<U> {
pub fn new(label: impl Into<String>, upstream: U) -> Self {
UpstreamVerifier {
label: label.into(),
help: String::new(),
generation: Vec::new(),
upstream,
}
}
pub fn with_help(mut self, help: impl Into<String>) -> Self {
self.help = help.into();
self
}
pub fn with_generation(mut self, generation: impl Into<Vec<u8>>) -> Self {
self.generation = generation.into();
self
}
pub fn provider(&self) -> &U {
&self.upstream
}
}
impl<U: UpstreamSignIn> CredentialVerifier for UpstreamVerifier<U> {
fn label(&self) -> &str {
&self.label
}
fn help(&self) -> &str {
&self.help
}
fn check<'a>(&'a self, _credential: &'a str) -> CheckFuture<'a> {
Box::pin(async { CredentialCheck::Invalid(None) })
}
fn accepts_bearer(&self) -> bool {
false
}
fn generation(&self) -> &[u8] {
&self.generation
}
fn upstream(&self) -> Option<&dyn UpstreamSignIn> {
Some(&self.upstream)
}
}
pub(crate) fn valid_subject(subject: &str) -> bool {
!subject.trim().is_empty()
&& subject.chars().count() <= MAX_SUBJECT_CHARS
&& !subject.chars().any(char::is_control)
}
#[cfg(test)]
mod tests {
use super::*;
struct Fake;
impl UpstreamSignIn for Fake {
fn provider(&self) -> &str {
"Fake"
}
fn authorize_url(&self, _redirect_uri: &str, _state: &str) -> String {
"https://fake.example.com/authorize".into()
}
fn exchange<'a>(&'a self, _code: &'a str, _redirect_uri: &'a str) -> ExchangeFuture<'a> {
Box::pin(async { Exchange::Refused("no".into()) })
}
}
#[test]
fn the_verifier_carries_credentials_but_never_takes_them_as_bearer_tokens() {
let v = UpstreamVerifier::new("Fake account", Fake)
.with_help("Sign in at Fake.")
.with_generation(b"live".to_vec());
assert_eq!(v.label(), "Fake account");
assert_eq!(v.help(), "Sign in at Fake.");
assert!(v.carried());
assert!(!v.accepts_bearer());
assert_eq!(v.generation(), b"live");
assert_eq!(v.upstream().map(|u| u.provider()), Some("Fake"));
}
#[tokio::test]
async fn the_verifier_rejects_anything_checked() {
let v = UpstreamVerifier::new("Fake account", Fake);
assert_eq!(v.check("anything").await, CredentialCheck::Invalid(None));
}
#[test]
fn grants_never_show_their_credential() {
let g = UpstreamGrant::new("secret-refresh-token").with_subject("user:1");
let shown = format!("{g:?}");
assert!(!shown.contains("secret"), "{shown}");
assert!(shown.contains("user:1"), "{shown}");
}
#[test]
fn subjects_are_short_printable_names() {
assert!(valid_subject("freeagent:user:123"));
for bad in ["", " ", "a\nb", &"x".repeat(MAX_SUBJECT_CHARS + 1)] {
assert!(!valid_subject(bad), "{bad:?}");
}
}
}