# apokalipto/devise_saml_authenticatable architecture

> Architecture diagram of the GitHub repository apokalipto/devise_saml_authenticatable, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-08-31). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/apokalipto/devise_saml_authenticatable
- Repository: https://github.com/apokalipto/devise_saml_authenticatable

## Overview

##### Project type and purpose
- This is a Ruby gem that integrates with Devise (a Rails authentication framework) to provide SAML-based Single Sign-On for Rails applications. It is not a full-stack app but an engine/plugin that you drop into your Rails stack.

##### File structure
- Top-level:
- Gemspec, Gemfile, Rakefile, CI config (.github/workflows/ci.yml) – typical of a Ruby library.
- `rails/init.rb` – Rails engine hook, registers routes and controllers into host app.
- `app/controllers/devise/saml_sessions_controller.rb` – SAML endpoints for AuthnRequest, metadata, logout.
- `lib/devise_saml_authenticatable/*.rb` – core library code: configuration (`saml_config`), strategy, response parsing, attribute mapping, entity ID reading, logging.
- `spec/` – thorough RSpec tests covering controllers, model integration, mapping resolvers, strategy, features.

##### README for additional insights
- Describes how to mount the gem in a Rails app (add to Gemfile, include `devise :saml_authenticatable` in your model).
- Lists the three user-facing endpoints: `/users/saml/auth`, `/users/saml/metadata`, `/users/saml/idp_sign_out`.
- Shows extension points: attribute-map resolver, IDP settings adapter, IDP entity ID reader, failed callback handler.
- Mentions dependency on the external `ruby-saml` library for all low-level SAML operations.

##### Main components
a. Rails Host Application
- Devise (User model + standard sessions)
- DeviseSamlAuthenticatable engine (mounted via `rails/init.rb`)
- Database (User table)
b. DeviseSamlAuthenticatable
- Controllers: `SamlSessionsController` (handles `/auth`, `/metadata`, `/idp_sign_out`)
- Strategy: `DeviseSamlAuthenticatable::Strategy` (hooked into Warden)
- Configuration: `SamlConfig`, `DefaultIdpEntityIdReader`, optional custom `IdpSettingsAdapter`
- Attribute mapping: `DefaultAttributeMapResolver` or custom resolver
- SAML processing: uses `ruby-saml` gem to build requests and parse responses (SamlResponse)
c. External Identity Provider (IdP)
- Receives AuthnRequest, authenticates user, returns SAMLResponse
d. Supporting libraries
- `ruby-saml` – builds/signs/parses SAML messages
- Rails & Devise internals

##### Relationships and interactions
1. User visits Rails app `GET /users/saml/sign_in` → SAML AuthnRequest generated
2. Redirect to IdP SSO endpoint
3. User logs into IdP → IdP POSTs SAMLResponse to `/users/saml/auth`
4. `SamlSessionsController` invokes `Strategy`:
- Validate signature, timestamps (via `ruby-saml`)
- `DefaultIdpEntityIdReader` picks the issuer
- `SamlConfig` obtains SP & IdP settings (possibly via adapter)
- `DefaultAttributeMapResolver` loads attribute map
- Gem locates or creates User (via `saml_resource_locator` and `saml_create_user`)
- Devise signs in the user and writes `session_index` if needed
5. (Optional) IdP-initiated logout → `/users/saml/idp_sign_out` tears down local session

##### Important architectural patterns
- Rails Engine: self-mounting plugin that injects routes, controllers, and Warden strategies into host.
- Strategy Pattern: `DeviseSamlAuthenticatable::Strategy` plugs into Devise/Warden pipeline.
- Adapter/Resolver Extension Points: settings adapter and attribute map resolver classes can be swapped out via config.
- Separation of Concerns:
- SAML transport/crypto (ruby-saml)
- Devise integration (strategy + hooks)
- Attribute mapping & entity ID reading

##### Final recommendations
- Be granular: show controllers, strategies, config, resolvers as separate nodes.
- Data flow and decision points (validation, mapping, user creation).
- External dependencies (ruby-saml) and the external IdP to make integration boundaries explicit.

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% User Interaction
    User("User Browser"):::external
    User -->|"GET /users/saml/sign_in"| SamlSessionsController

    %% Host App Components
    subgraph "Rails Host App" 
        direction TB
        Devise["Devise (User Model & Sessions)"]:::host
        Database["Database (User table)"]:::host
    end

    %% Gem Components
    subgraph "DeviseSamlAuthenticatable Gem"
        direction TB
        RailsInit["Rails Engine Initializer"]:::gem
        RoutesDef["Routes Definition"]:::gem
        SamlSessionsController["SAMLSessionsController<br/>(/auth, /metadata, /idp_sign_out)"]:::gem
        Strategy["Devise/Warden Strategy"]:::gem
        ConfigLoader["SAML Configuration Loader"]:::gem
        IdpReader["DefaultIdP Entity ID Reader"]:::optional
        AttrResolver["Default Attribute Map Resolver"]:::optional
        ResponseParser["SAML Response Parser & Validator"]:::gem
        AttrMapper["SAML Attribute Mapping Helper"]:::gem
        ModelIntegration["Devise Model Integration Helpers"]:::gem
        Logger["Internal Logging Utility"]:::gem
        Exceptions["Custom Exception Types"]:::gem
        CoreEntry["Core Library Entry Point"]:::gem
    end

    %% External Dependencies
    rubySaml["ruby-saml Library"]:::external
    IdP["External Identity Provider"]:::external

    %% Data Flow
    SamlSessionsController -->|"build AuthnRequest"| ConfigLoader
    ConfigLoader --> rubySaml
    ConfigLoader -->|uses| IdpReader
    ConfigLoader -->|uses| AttrResolver
    ConfigLoader -->|configures| Strategy
    Strategy --> rubySaml
    rubySaml -->|signed AuthnRequest| IdP

    IdP -->|"POST SAMLResponse"| SamlSessionsController
    SamlSessionsController --> ResponseParser
    ResponseParser -->|validate & parse| rubySaml
    ResponseParser -->|extract attributes| AttrMapper
    AttrMapper -->|mapped attrs| ModelIntegration
    ModelIntegration -->|find/create user| Database
    ModelIntegration -->|session_index| Devise
    SamlSessionsController -->|sign in user| Devise

    %% Mounting and Initialization
    RailsInit --> RoutesDef
    RoutesDef --> SamlSessionsController

    %% Associations
    Devise -->|uses strategy| Strategy
    Strategy -->|callback| SamlSessionsController

    %% Click Events
    click RailsInit "https://github.com/apokalipto/devise_saml_authenticatable/blob/master/rails/init.rb"
    click RoutesDef "https://github.com/apokalipto/devise_saml_authenticatable/blob/master/lib/devise_saml_authenticatable/routes.rb"
    click SamlSessionsController "https://github.com/apokalipto/devise_saml_authenticatable/blob/master/app/controllers/devise/saml_sessions_controller.rb"
    click Strategy "https://github.com/apokalipto/devise_saml_authenticatable/blob/master/lib/devise_saml_authenticatable/strategy.rb"
    click ConfigLoader "https://github.com/apokalipto/devise_saml_authenticatable/blob/master/lib/devise_saml_authenticatable/saml_config.rb"
    click IdpReader "https://github.com/apokalipto/devise_saml_authenticatable/blob/master/lib/devise_saml_authenticatable/default_idp_entity_id_reader.rb"
    click AttrResolver "https://github.com/apokalipto/devise_saml_authenticatable/blob/master/lib/devise_saml_authenticatable/default_attribute_map_resolver.rb"
    click ResponseParser "https://github.com/apokalipto/devise_saml_authenticatable/blob/master/lib/devise_saml_authenticatable/saml_response.rb"
    click AttrMapper "https://github.com/apokalipto/devise_saml_authenticatable/blob/master/lib/devise_saml_authenticatable/saml_mapped_attributes.rb"
    click ModelIntegration "https://github.com/apokalipto/devise_saml_authenticatable/blob/master/lib/devise_saml_authenticatable/model.rb"
    click Logger "https://github.com/apokalipto/devise_saml_authenticatable/blob/master/lib/devise_saml_authenticatable/logger.rb"
    click Exceptions "https://github.com/apokalipto/devise_saml_authenticatable/blob/master/lib/devise_saml_authenticatable/exception.rb"
    click CoreEntry "https://github.com/apokalipto/devise_saml_authenticatable/blob/master/lib/devise_saml_authenticatable.rb"

    %% Styles
    classDef host fill:#D0E8FF,stroke:#036;
    classDef gem fill:#D0F0D0,stroke:#060;
    classDef external fill:#FFE8A0,stroke:#E08;
    classDef optional stroke-dasharray: 5 5;
```
