Skip to content

Commit

Permalink
better logging when running in docker container
Browse files Browse the repository at this point in the history
  • Loading branch information
johanlundberg committed Oct 30, 2023
1 parent 9b38333 commit e01c242
Show file tree
Hide file tree
Showing 17 changed files with 25 additions and 54 deletions.
7 changes: 2 additions & 5 deletions src/auth_server/api.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# -*- coding: utf-8 -*-
import logging
from typing import Dict, Type, cast

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger
from starlette.staticfiles import StaticFiles

from auth_server.config import AuthServerConfig, ConfigurationError, FlowName, load_config
Expand All @@ -20,14 +20,11 @@
__author__ = "lundberg"


logger = logging.getLogger(__name__)


class AuthServer(FastAPI):
def __init__(self):
config = load_config()
super().__init__(root_path=config.application_root)
init_logging(level=config.log_level)
init_logging(level=config.log_level, colorize=config.log_color, fmt=config.log_format)

# Load flows
self.builtin_flow: Dict[FlowName, Type[BaseAuthFlow]] = {
Expand Down
2 changes: 2 additions & 0 deletions src/auth_server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ class AuthServerConfig(BaseSettings):
environment: Environment = Field(default=Environment.PROD)
testing: bool = False
log_level: str = Field(default="INFO")
log_color: bool = True
log_format: Optional[str] = None
host: str = Field(default="0.0.0.0")
port: int = Field(default=8080)
application_root: str = Field(default="")
Expand Down
4 changes: 1 addition & 3 deletions src/auth_server/db/client.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
# -*- coding: utf-8 -*-
import logging
from typing import Any, AsyncGenerator, Dict, List, Mapping, Optional, Union

from bson import ObjectId
from loguru import logger
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo import MongoClient, WriteConcern

from auth_server.config import load_config

__author__ = "lundberg"

logger = logging.getLogger(__name__)


async def get_motor_client() -> Optional[AsyncIOMotorClient]:
config = load_config()
Expand Down
4 changes: 1 addition & 3 deletions src/auth_server/flows.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
# -*- coding: utf-8 -*-
from __future__ import annotations

import logging
from abc import ABC
from typing import Any, List, Mapping, Optional, Union

from fastapi import HTTPException
from jwcrypto import jwt
from jwcrypto.jwk import JWK
from loguru import logger

from auth_server.config import AuthServerConfig
from auth_server.context import ContextRequest
Expand Down Expand Up @@ -51,8 +51,6 @@

__author__ = "lundberg"

logger = logging.getLogger(__name__)


# Use this to go to next flow
class NextFlowException(HTTPException):
Expand Down
6 changes: 5 additions & 1 deletion src/auth_server/log.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
import logging
import sys
from typing import Optional

from loguru import logger

Expand All @@ -11,6 +12,7 @@


class InterceptHandler(logging.Handler):
@logger.catch(default=True, onerror=lambda _: sys.exit(1))
def emit(self, record):
# Get corresponding Loguru level if it exists
try:
Expand All @@ -33,9 +35,11 @@ def emit(self, record):

def init_logging(
level: str = "INFO",
fmt=LOGURU_FORMAT,
colorize: bool = True,
fmt: Optional[str] = None,
) -> None:
if fmt is None:
fmt = LOGURU_FORMAT
logger.remove() # Remove the default handler
logger.add(sys.stderr, format=fmt, colorize=colorize, level="ERROR", enqueue=True)
logger.add(sys.stdout, format=fmt, colorize=colorize, level=level, enqueue=True)
5 changes: 1 addition & 4 deletions src/auth_server/mdq.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
import logging
from base64 import b64encode
from collections import OrderedDict as _OrderedDict
from enum import Enum
Expand All @@ -9,6 +8,7 @@
import xmltodict
from cryptography.hazmat.primitives.hashes import SHA1, SHA256
from cryptography.x509 import Certificate
from loguru import logger
from pydantic import BaseModel, Field, validator
from pyexpat import ExpatError

Expand All @@ -21,9 +21,6 @@
__author__ = "lundberg"


logger = logging.getLogger(__name__)


class KeyUse(str, Enum):
SIGNING = "signing"
ENCRYPTION = "encryption"
Expand Down
6 changes: 1 addition & 5 deletions src/auth_server/middleware.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
# -*- coding: utf-8 -*-
import logging

from jwcrypto import jws
from jwcrypto.common import JWException
from loguru import logger
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import PlainTextResponse
Expand All @@ -13,9 +12,6 @@
__author__ = "lundberg"


logger = logging.getLogger(__name__)


# middleware needs to return a reponse
# some background: https://github.com/tiangolo/fastapi/issues/458
def return_error_response(status_code: int, detail: str):
Expand Down
6 changes: 2 additions & 4 deletions src/auth_server/proof/common.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
# -*- coding: utf-8 -*-

import logging
from typing import Optional

from loguru import logger

from auth_server.config import ClientKey, ConfigurationError, load_config
from auth_server.models.gnap import Key
from auth_server.models.jose import ECJWK, RSAJWK, KeyType, SymmetricJWK

__author__ = "lundberg"


logger = logging.getLogger(__name__)


async def load_config_key(client_key: ClientKey) -> Key:
logger.info("Trying to load client key from config")
logger.debug(f"client_key: {client_key}")
Expand Down
5 changes: 1 addition & 4 deletions src/auth_server/proof/jws.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# -*- coding: utf-8 -*-
import logging
from base64 import urlsafe_b64encode
from typing import Optional, Union

from cryptography.hazmat.primitives.hashes import SHA256, SHA384, SHA512
from fastapi import HTTPException
from jwcrypto import jwk, jws
from jwcrypto.common import base64url_encode
from loguru import logger
from pydantic import ValidationError

from auth_server.config import load_config
Expand All @@ -19,9 +19,6 @@
__author__ = "lundberg"


logger = logging.getLogger(__name__)


async def choose_hash_alg(alg: SupportedAlgorithms):
# TODO: what about EdDSA
if alg.name.endswith("256"):
Expand Down
5 changes: 1 addition & 4 deletions src/auth_server/proof/mtls.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
# -*- coding: utf-8 -*-

import logging
from base64 import b64encode

from cryptography.hazmat.primitives.hashes import SHA256
from loguru import logger

from auth_server.models.gnap import Key
from auth_server.utils import load_cert_from_str

__author__ = "lundberg"


logger = logging.getLogger(__name__)


async def check_mtls_proof(gnap_key: Key, cert: str) -> bool:
try:
tls_cert = load_cert_from_str(cert)
Expand Down
4 changes: 1 addition & 3 deletions src/auth_server/routers/interaction.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# -*- coding: utf-8 -*-
__author__ = "lundberg"

import logging
from pathlib import Path
from typing import Optional

from fastapi import APIRouter, BackgroundTasks, Form, HTTPException
from loguru import logger
from starlette.responses import HTMLResponse, RedirectResponse, Response

from auth_server.config import load_config
Expand All @@ -15,8 +15,6 @@
from auth_server.templating import TestableJinja2Templates
from auth_server.utils import get_interaction_hash, push_interaction_finish

logger = logging.getLogger(__name__)

interaction_router = APIRouter(route_class=ContextRequestRoute, prefix="/interaction")
templates = TestableJinja2Templates(directory=str(Path(__file__).with_name("templates")))

Expand Down
4 changes: 1 addition & 3 deletions src/auth_server/routers/root.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# -*- coding: utf-8 -*-
import logging
from typing import Optional

from fastapi import APIRouter, Depends, Header, HTTPException
from jwcrypto.jwk import JWK, JWKSet
from loguru import logger
from starlette.responses import Response

from auth_server.config import AuthServerConfig, load_config
Expand All @@ -17,8 +17,6 @@
__author__ = "lundberg"


logger = logging.getLogger(__name__)

root_router = APIRouter(route_class=ContextRequestRoute, prefix="")


Expand Down
4 changes: 1 addition & 3 deletions src/auth_server/routers/saml2_sp.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# -*- coding: utf-8 -*-
__author__ = "lundberg"

import logging
import uuid
from pathlib import Path
from typing import Optional

from fastapi import APIRouter, Form, HTTPException, Query, Response
from loguru import logger
from saml2.metadata import entity_descriptor
from starlette.responses import HTMLResponse, RedirectResponse

Expand All @@ -25,8 +25,6 @@
)
from auth_server.templating import TestableJinja2Templates

logger = logging.getLogger(__name__)

saml2_router = APIRouter(route_class=ContextRequestRoute, prefix="/saml2")
templates = TestableJinja2Templates(directory=str(Path(__file__).with_name("templates")))

Expand Down
4 changes: 1 addition & 3 deletions src/auth_server/routers/status.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
import asyncio
import logging

from fastapi import APIRouter
from loguru import logger
from pymongo.errors import ConnectionFailure

from auth_server.config import load_config
Expand All @@ -12,8 +12,6 @@
__author__ = "lundberg"


logger = logging.getLogger(__name__)

status_router = APIRouter(prefix="/status")


Expand Down
4 changes: 1 addition & 3 deletions src/auth_server/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
from __future__ import annotations

import atexit
import logging
import random
import shutil
import subprocess
Expand All @@ -39,15 +38,14 @@
from abc import ABC, abstractmethod
from typing import Any, Optional, Sequence, Type, cast

from loguru import logger
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure

from auth_server.time_utils import utc_now

__author__ = "lundberg"

logger = logging.getLogger(__name__)


class TemporaryInstance(ABC):
"""Singleton to manage a temporary instance of something needed when testing.
Expand Down
4 changes: 1 addition & 3 deletions src/auth_server/tls_fed_auth.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
import base64
import json
import logging
from datetime import datetime, timedelta
from pathlib import Path
from typing import List, Mapping, Optional
Expand All @@ -12,6 +11,7 @@
from cryptography.hazmat.primitives.hashes import SHA256
from cryptography.x509 import load_pem_x509_certificate
from jwcrypto import jwk, jws
from loguru import logger
from pydantic import BaseModel, ValidationError

from auth_server.config import load_config
Expand All @@ -23,8 +23,6 @@

__author__ = "lundberg"

logger = logging.getLogger(__name__)


class MetadataSource(BaseModel):
issued_at: datetime
Expand Down
5 changes: 2 additions & 3 deletions src/auth_server/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
import importlib
import json
import logging
from base64 import urlsafe_b64encode
from functools import lru_cache
from typing import Any, Callable, Generator, Mapping, Sequence, Union
Expand All @@ -13,14 +12,14 @@
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.x509 import Certificate, load_pem_x509_certificate
from jwcrypto import jwk
from loguru import logger

from auth_server.config import ConfigurationError, load_config

__author__ = "lundberg"

from auth_server.models.gnap import HashMethod

logger = logging.getLogger(__name__)
from auth_server.models.gnap import HashMethod


@lru_cache()
Expand Down

0 comments on commit e01c242

Please sign in to comment.