Skip to content

Commit

Permalink
Re-use bluesky-stomp BasicAuthenticationg
Browse files Browse the repository at this point in the history
  • Loading branch information
DiamondJoseph committed Sep 17, 2024
1 parent 9d7414b commit eb34120
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 77 deletions.
89 changes: 42 additions & 47 deletions helm/blueapi/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,16 @@ serviceAccount:

podAnnotations: {}

podSecurityContext:
{}
# fsGroup: 2000

securityContext:
{}
# capabilities:
# drop:
# - ALL
# readOnlyRootFilesystem: true
# runAsNonRoot: true
# runAsUser: 1000
podSecurityContext: {}
# fsGroup: 2000

securityContext: {}
# capabilities:
# drop:
# - ALL
# readOnlyRootFilesystem: true
# runAsNonRoot: true
# runAsUser: 1000

# Recommended for production to change service.type to ClusterIP and set up an Ingress
service:
Expand All @@ -47,23 +45,21 @@ ingress:
create: false
# host: foo.diamond.ac.uk (assumes port = service.port)

resources:
{}
# We usually recommend not to specify default resources and to leave this as a conscious
# choice for the user. This also increases chances charts run on environments with little
# resources, such as Minikube. If you do want to specify resources, uncomment the following
# lines, adjust them as necessary, and remove the curly braces after 'resources:'.
# limits:
# cpu: 100m
# memory: 128Mi
# requests:
# cpu: 100m
# memory: 128Mi

initResources:
{}
# Can optionally specify separate resource constraints for the scratch setup container.
# If left empty this defaults to the same as resources above.
resources: {}
# We usually recommend not to specify default resources and to leave this as a conscious
# choice for the user. This also increases chances charts run on environments with little
# resources, such as Minikube. If you do want to specify resources, uncomment the following
# lines, adjust them as necessary, and remove the curly braces after 'resources:'.
# limits:
# cpu: 100m
# memory: 128Mi
# requests:
# cpu: 100m
# memory: 128Mi

initResources: {}
# Can optionally specify separate resource constraints for the scratch setup container.
# If left empty this defaults to the same as resources above.

nodeSelector: {}

Expand All @@ -80,13 +76,12 @@ listener:
resources: {}

# Additional envVars to mount to the pod as a String
extraEnvVars:
[]
# - name: RABBITMQ_PASSWORD
# valueFrom:
# secretKeyRef:
# name: rabbitmq-password
# key: rabbitmq-password
extraEnvVars: []
# - name: RABBITMQ_PASSWORD
# valueFrom:
# secretKeyRef:
# name: rabbitmq-password
# key: rabbitmq-password

# Config for the worker goes here, will be mounted into a config file
worker:
Expand All @@ -95,27 +90,27 @@ worker:
port: 8000
env:
sources:
- kind: deviceFunctions
module: blueapi.startup.example_devices
- kind: planFunctions
module: blueapi.startup.example_plans
- kind: planFunctions
module: dls_bluesky_core.plans
- kind: planFunctions
module: dls_bluesky_core.stubs
- kind: deviceFunctions
module: blueapi.startup.example_devices
- kind: planFunctions
module: blueapi.startup.example_plans
- kind: planFunctions
module: dls_bluesky_core.plans
- kind: planFunctions
module: dls_bluesky_core.stubs
stomp:
auth:
username: guest
passcode: guest
password: guest
host: rabbitmq
port: 61613

initContainer:
scratch:
root: /blueapi-plugins/scratch
repositories: []
# - name: "dodal"
# remote_url: https://github.com/DiamondLightSource/dodal.git
# - name: "dodal"
# remote_url: https://github.com/DiamondLightSource/dodal.git

# Mount path for scratch area from host machine, setting
# this effectively enables scratch area management
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ dependencies = [
"dls-dodal>=1.31.0",
"super-state-machine", # See GH issue 553
"GitPython",
"bluesky-stomp>=0.1.0",
"bluesky-stomp>=0.1.1",
]
dynamic = ["version"]
license.file = "LICENSE"
Expand Down
23 changes: 2 additions & 21 deletions src/blueapi/config.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import os
from collections.abc import Mapping
from enum import Enum
from pathlib import Path
from typing import Any, Generic, Literal, TypeVar

import yaml
from pydantic import BaseModel, Field, TypeAdapter, ValidationError, field_validator
from bluesky_stomp.models import BasicAuthentication
from pydantic import BaseModel, Field, TypeAdapter, ValidationError

from blueapi.utils import BlueapiBaseModel, InvalidConfigError

Expand All @@ -23,25 +23,6 @@ class Source(BaseModel):
module: Path | str


class BasicAuthentication(BaseModel):
"""
Log in details for when a server uses authentication.
If username or passcode match exactly the regex ^\\${(.*)}$
they attempt to replace with an environment variable of the same.
i.e. ${foo} or ${FOO} are replaced with the value of FOO
"""

username: str = "guest"
passcode: str = "guest"

@field_validator("username", "passcode")
@classmethod
def get_from_env(cls, v: str):
if v.startswith("${") and v.endswith("}"):
return os.environ[v.removeprefix("${").removesuffix("}").upper()]
return v


class StompConfig(BaseModel):
"""
Config for connecting to stomp broker
Expand Down
17 changes: 9 additions & 8 deletions tests/unit_tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
from unittest import mock

import pytest
from bluesky_stomp.models import BasicAuthentication
from pydantic import BaseModel, Field

from blueapi.config import BasicAuthentication, ConfigLoader
from blueapi.config import ConfigLoader
from blueapi.utils import InvalidConfigError


Expand Down Expand Up @@ -121,28 +122,28 @@ def test_error_thrown_if_schema_does_not_match_yaml(nested_config_yaml: Path) ->

@mock.patch.dict(os.environ, {"FOO": "bar"}, clear=True)
def test_auth_from_env():
auth = BasicAuthentication(username="${FOO}", passcode="baz")
auth = BasicAuthentication(username="${FOO}", password="baz")
assert auth.username == "bar"


@mock.patch.dict(os.environ, {"FOO": "bar", "BAZ": "qux"}, clear=True)
def test_auth_from_env_repeated_key():
auth = BasicAuthentication(username="${FOO}", passcode="${FOO}")
auth = BasicAuthentication(username="${FOO}", password="${FOO}")
assert auth.username == "bar"
assert auth.passcode == "bar"
assert auth.password == "bar"


@mock.patch.dict(os.environ, {"FOO": "bar"}, clear=True)
def test_auth_from_env_ignore_case():
auth = BasicAuthentication(username="${FOO}", passcode="${foo}")
auth = BasicAuthentication(username="${FOO}", password="${foo}")
assert auth.username == "bar"
assert auth.passcode == "bar"
assert auth.password == "bar"


@mock.patch.dict(os.environ, {"FOO": "bar"}, clear=True)
def test_auth_from_env_throws_when_not_available():
# Eagerly throws an exception, will fail during initial loading
with pytest.raises(KeyError):
BasicAuthentication(username="${BAZ}", passcode="baz")
BasicAuthentication(username="${BAZ}", password="baz")
with pytest.raises(KeyError):
BasicAuthentication(username="${baz}", passcode="baz")
BasicAuthentication(username="${baz}", password="baz")

0 comments on commit eb34120

Please sign in to comment.