Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable authorization directives by default #3713

Merged
merged 26 commits into from
Oct 23, 2023
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
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
5 changes: 5 additions & 0 deletions .changesets/feat_geal_authz_optout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
### Authorization directives are enabled by default ([Issue #3842](https://github.com/apollographql/router/issues/3842))

If the router starts with an API key from an Enterprise account, and the schema contains the authorization directives, then they will be usable directly wxithout further configuration.
Geal marked this conversation as resolved.
Show resolved Hide resolved

By [@Geal](https://github.com/Geal) in https://github.com/apollographql/router/pull/3713
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ expression: "&schema"
"properties": {
"enabled": {
"description": "enables the `@authenticated` and `@requiresScopes` directives",
"default": false,
"default": true,
"type": "boolean"
}
}
Expand Down
19 changes: 7 additions & 12 deletions apollo-router/src/plugins/authorization/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ use self::scopes::ScopeExtractionVisitor;
use self::scopes::ScopeFilteringVisitor;
use self::scopes::REQUIRES_SCOPES_DIRECTIVE_NAME;
use crate::error::QueryPlannerError;
use crate::error::SchemaError;
use crate::error::ServiceBuildError;
use crate::graphql;
use crate::json_ext::Path;
Expand Down Expand Up @@ -76,10 +75,14 @@ pub(crate) struct Conf {
#[allow(dead_code)]
pub(crate) struct Directives {
/// enables the `@authenticated` and `@requiresScopes` directives
#[serde(default)]
#[serde(default = "default_enable_directives")]
enabled: bool,
}

fn default_enable_directives() -> bool {
true
}

pub(crate) struct AuthorizationPlugin {
require_authentication: bool,
}
Expand All @@ -96,6 +99,7 @@ impl AuthorizationPlugin {
.find(|(s, _)| s.as_str() == "authorization")
.and_then(|(_, v)| v.get("preview_directives").and_then(|v| v.as_object()))
.and_then(|v| v.get("enabled").and_then(|v| v.as_bool()));

let has_authorization_directives = schema
.definitions
.directive_definitions
Expand All @@ -109,16 +113,7 @@ impl AuthorizationPlugin {
.directive_definitions
.contains_key(POLICY_DIRECTIVE_NAME);

match has_config {
Some(b) => Ok(b),
None => {
if has_authorization_directives {
Err(ServiceBuildError::Schema(SchemaError::Api("cannot start the router on a schema with authorization directives without configuring the authorization plugin".to_string())))
} else {
Ok(false)
}
}
}
Ok(has_config.unwrap_or(true) && has_authorization_directives)
}

pub(crate) async fn query_analysis(
Expand Down
3 changes: 3 additions & 0 deletions apollo-router/src/spec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ use thiserror::Error;
use crate::graphql::ErrorExtension;
use crate::json_ext::Object;

pub(crate) const LINK_DIRECTIVE_NAME: &str = "link";
pub(crate) const LINK_URL_ARGUMENT: &str = "url";

/// GraphQL parsing errors.
#[derive(Error, Debug, Display, Clone, Serialize, Deserialize)]
#[non_exhaustive]
Expand Down
19 changes: 19 additions & 0 deletions apollo-router/src/spec/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,25 @@ impl Schema {
Ok(schema)
}

pub(crate) fn make_compiler(sdl: &str) -> Result<ApolloCompiler, SchemaError> {
let mut compiler = ApolloCompiler::new();
let id = compiler.add_type_system(sdl, "schema.graphql");

let ast = compiler.db.ast(id);

// Trace log recursion limit data
let recursion_limit = ast.recursion_limit();
tracing::trace!(?recursion_limit, "recursion limit data");

let mut parse_errors = ast.errors().peekable();
if parse_errors.peek().is_some() {
let errors = parse_errors.cloned().collect::<Vec<_>>();
return Err(SchemaError::Parse(ParseErrors { errors }));
}

Ok(compiler)
}

pub(crate) fn parse(sdl: &str, configuration: &Configuration) -> Result<Self, SchemaError> {
let start = Instant::now();
let mut parser = apollo_compiler::Parser::new();
Expand Down
9 changes: 7 additions & 2 deletions apollo-router/src/state_machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ use crate::configuration::ListenAddr;
use crate::router::Event::UpdateLicense;
use crate::router_factory::RouterFactory;
use crate::router_factory::RouterSuperServiceFactory;
use crate::spec::Schema;
use crate::uplink::license_enforcement::LicenseEnforcementReport;
use crate::uplink::license_enforcement::LicenseState;
use crate::uplink::license_enforcement::LICENSE_EXPIRED_URL;
Expand Down Expand Up @@ -316,8 +317,12 @@ impl<FA: RouterSuperServiceFactory> State<FA> {
S: HttpServerFactory,
FA: RouterSuperServiceFactory,
{
// Check the license
let report = LicenseEnforcementReport::build(&configuration);
let report = {
let parsed_schema = Schema::make_compiler(&schema)
.map_err(|e| ServiceCreationError(e.to_string().into()))?;
// Check the license
LicenseEnforcementReport::build(&configuration, &parsed_schema)
};

match license {
LicenseState::Licensed => {
Expand Down
120 changes: 107 additions & 13 deletions apollo-router/src/uplink/license_enforcement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@
// Read more: https://github.com/hyperium/tonic/issues/1056
#![allow(clippy::derive_partial_eq_without_eq)]

use std::collections::HashSet;
use std::fmt::Display;
use std::fmt::Formatter;
use std::str::FromStr;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;

use apollo_compiler::ApolloCompiler;
use apollo_compiler::HirDatabase;
use buildstructor::Builder;
use displaydoc::Display;
use itertools::Itertools;
Expand All @@ -25,6 +28,8 @@ use serde::Serialize;
use serde_json::Value;
use thiserror::Error;

use crate::spec::LINK_DIRECTIVE_NAME;
use crate::spec::LINK_URL_ARGUMENT;
use crate::Configuration;

pub(crate) const LICENSE_EXPIRED_URL: &str = "https://go.apollo.dev/o/elp";
Expand Down Expand Up @@ -75,19 +80,24 @@ where
#[derive(Debug)]
pub(crate) struct LicenseEnforcementReport {
restricted_config_in_use: Vec<ConfigurationRestriction>,
restricted_schema_in_use: Vec<SchemaRestriction>,
}

impl LicenseEnforcementReport {
pub(crate) fn uses_restricted_features(&self) -> bool {
!self.restricted_config_in_use.is_empty()
!self.restricted_config_in_use.is_empty() || !self.restricted_schema_in_use.is_empty()
}

pub(crate) fn build(configuration: &Configuration) -> LicenseEnforcementReport {
pub(crate) fn build(
configuration: &Configuration,
schema: &ApolloCompiler,
) -> LicenseEnforcementReport {
LicenseEnforcementReport {
restricted_config_in_use: Self::validate_configuration(
configuration,
&Self::configuration_restrictions(),
),
restricted_schema_in_use: Self::validate_schema(schema, &Self::schema_restrictions()),
}
}

Expand Down Expand Up @@ -119,6 +129,31 @@ impl LicenseEnforcementReport {
configuration_violations
}

fn validate_schema(
schema: &ApolloCompiler,
schema_restrictions: &Vec<SchemaRestriction>,
) -> Vec<SchemaRestriction> {
let feature_urls = schema
.db
.schema()
.directives_by_name(LINK_DIRECTIVE_NAME)
.filter_map(|link| {
link.argument_by_name(LINK_URL_ARGUMENT)
.and_then(|value| value.as_str().map(|s| s.to_string()))
})
.collect::<HashSet<_>>();

let mut schema_violations = Vec::new();

for restriction in schema_restrictions {
if feature_urls.contains(&restriction.url) {
schema_violations.push(restriction.clone());
}
}

schema_violations
}

fn configuration_restrictions() -> Vec<ConfigurationRestriction> {
vec![
ConfigurationRestriction::builder()
Expand Down Expand Up @@ -183,17 +218,47 @@ impl LicenseEnforcementReport {
.build(),
]
}

fn schema_restrictions() -> Vec<SchemaRestriction> {
vec![
SchemaRestriction::builder()
.name("@authenticated")
.url("https://specs.apollo.dev/authenticated/v0.1")
Geal marked this conversation as resolved.
Show resolved Hide resolved
.build(),
SchemaRestriction::builder()
.name("@requiresScopes")
.url("https://specs.apollo.dev/requiresScopes/v0.1")
Geal marked this conversation as resolved.
Show resolved Hide resolved
.build(),
]
}
}

impl Display for LicenseEnforcementReport {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let restricted_config = self
.restricted_config_in_use
.iter()
.map(|v| format!("* {}\n {}", v.name, v.path.replace("$.", ".")))
.join("\n\n");
if !self.restricted_config_in_use.is_empty() {
let restricted_config = self
.restricted_config_in_use
.iter()
.map(|v| format!("* {}\n {}", v.name, v.path.replace("$.", ".")))
.join("\n\n");
write!(f, "Configuration yaml:\n{restricted_config}")?;

if !self.restricted_schema_in_use.is_empty() {
writeln!(f)?;
}
}

if !self.restricted_schema_in_use.is_empty() {
let restricted_schema = self
.restricted_schema_in_use
.iter()
.map(|v| format!("* {}\n {}", v.name, v.url))
.join("\n\n");

write!(f, "Configuration yaml:\n{restricted_config}")
write!(f, "Schema features:\n{restricted_schema}")?
}

Ok(())
}
}

Expand Down Expand Up @@ -277,6 +342,13 @@ pub(crate) struct ConfigurationRestriction {
value: Option<Value>,
}

/// An individual check for the supergraph schema
#[derive(Builder, Clone, Debug, Serialize, Deserialize)]
pub(crate) struct SchemaRestriction {
name: String,
url: String,
}

impl License {
pub(crate) fn jwks() -> &'static JwkSet {
JWKS.get_or_init(|| {
Expand All @@ -297,22 +369,27 @@ mod test {
use insta::assert_snapshot;
use serde_json::json;

use crate::spec::Schema;
use crate::uplink::license_enforcement::Audience;
use crate::uplink::license_enforcement::Claims;
use crate::uplink::license_enforcement::License;
use crate::uplink::license_enforcement::LicenseEnforcementReport;
use crate::uplink::license_enforcement::OneOrMany;
use crate::Configuration;

fn check(router_yaml: &str) -> LicenseEnforcementReport {
fn check(router_yaml: &str, supergraph_schema: &str) -> LicenseEnforcementReport {
let config = Configuration::from_str(router_yaml).expect("router config must be valid");

LicenseEnforcementReport::build(&config)
let schema =
Schema::make_compiler(supergraph_schema).expect("supergraph schema must be valid");
LicenseEnforcementReport::build(&config, &schema)
}

#[test]
fn test_oss() {
let report = check(include_str!("testdata/oss.router.yaml"));
let report = check(
include_str!("testdata/oss.router.yaml"),
include_str!("testdata/oss.graphql"),
);

assert!(
report.restricted_config_in_use.is_empty(),
Expand All @@ -322,7 +399,10 @@ mod test {

#[test]
fn test_restricted_features_via_config() {
let report = check(include_str!("testdata/restricted.router.yaml"));
let report = check(
include_str!("testdata/restricted.router.yaml"),
include_str!("testdata/oss.graphql"),
);

assert!(
!report.restricted_config_in_use.is_empty(),
Expand All @@ -331,6 +411,20 @@ mod test {
assert_snapshot!(report.to_string());
}

#[test]
fn test_restricted_authorization_directives_via_schema() {
let report = check(
include_str!("testdata/oss.router.yaml"),
include_str!("testdata/authorization.graphql"),
);

assert!(
!report.restricted_schema_in_use.is_empty(),
"should have found restricted features"
);
assert_snapshot!(report.to_string());
}

#[test]
fn test_license_parse() {
let license = License::from_str("eyJhbGciOiJFZERTQSJ9.eyJpc3MiOiJodHRwczovL3d3dy5hcG9sbG9ncmFwaHFsLmNvbS8iLCJzdWIiOiJhcG9sbG8iLCJhdWQiOiJTRUxGX0hPU1RFRCIsIndhcm5BdCI6MTY3NjgwODAwMCwiaGFsdEF0IjoxNjc4MDE3NjAwfQ.tXexfjZ2SQeqSwkWQ7zD4XBoxS_Hc5x7tSNJ3ln-BCL_GH7i3U9hsIgdRQTczCAjA_jjk34w39DeSV0nTc5WBw").expect("must be able to decode JWT");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
source: apollo-router/src/uplink/license_enforcement.rs
expression: report.to_string()
---
Schema features:
* @authenticated
https://specs.apollo.dev/authenticated/v0.1

* @requiresScopes
https://specs.apollo.dev/requiresScopes/v0.1
Loading