型レベルセキュリティ:安全なAIコード生成の未来とは?
2026年6月4日
11 分で読めますはじめに
コードの
Rustの
この
型を使う理由
型システムをadd関数をint型だけが
私の
セキュリティ脆弱性の
Trusted Types
この
Linuxカーネルでも、__userマクロを
以降では、
IDORを解決する
Insecure Direct Object Reference
統計的に、
Pythonの場合
まず、
import sqlite3
from fastapi import FastAPI, Depends
app = FastAPI()
DATABASE = "app.db"
def get_db():
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
try:
yield conn
finally:
conn.close()
@app.get("/balance/{user_id}")
def get_balance(user_id: int, db: sqlite3.Connection = Depends(get_db)):
cursor = db.execute(f"SELECT balance FROM accounts WHERE user_id = {user_id}")
row = cursor.fetchone()
return {"uid": user_id, "balance": row["balance"]}これは
@app.get("/balance/{user_id}")
def get_balance(user_id: int, db: sqlite3.Connection = Depends(get_db)):
if not (check_authentication() and check_authorization()): return 403
...これで
import sqlite3
from fastapi import FastAPI, Depends
from typing import Never, NewType, Final
from collections.abc import Generator
from contextlib import contextmanager
app = FastAPI()
DATABASE = "app.db"
def get_db():
...
UserID = NewType("UserID", int)
class AuthenticationProvider:
def do_authn(self) -> "AuthenticationGuard":
# do something to check the auth
return AuthenticationGuard(guard=AuthenticationGuard._INSTANTIATION_TOKEN) # pyright: ignore[reportPrivateUsage, reportArgumentType]
class AuthenticationGuard:
_INSTANTIATION_TOKEN: Final = object()
def __init__(self, *, guard: Never):
# could also do some runtime checks to ensure caller
assert guard is self._INSTANTIATION_TOKEN
class UncheckedUserID:
__value: UserID
def __init__(self, user_id: UserID):
self.__value = user_id
@contextmanager
def ensure_authn(self, guard: AuthenticationGuard) -> Generator[UserID, None, None]:
assert guard
yield self.__value
@app.get("/balance/{user_id}")
def get_balance(unauth_user_id: UncheckedUserID = Depends(UncheckedUserID), db: sqlite3.Connection = Depends(get_db)):
authguard = AuthenticationProvider().do_authn()
with unauth_user_id.ensure_authn(authguard) as user_id:
cursor = db.execute(f"SELECT balance FROM accounts WHERE user_id = {user_id}")
row = cursor.fetchone()
return {"uid": user_id, "balance": row["balance"]}コードは
新しいintのようなUncheckedUserIDクラスがuser_id値を
PythonはAuthenticationGuardを
Rustの場合
Rustの
use axum::{response::IntoResponse, routing::get, Json, Router};
mod unchecked_input {
use axum::extract::{FromRequestParts, Path};
#[derive(serde::Deserialize, serde::Serialize, Debug)]
pub struct UserID(u32);
#[derive(FromRequestParts)]
pub struct UncheckedUserID {
#[from_request(via(Path))]
value: UserID,
}
impl UncheckedUserID {
pub const fn ensure_authn(self, _: super::authentication::AuthenticationGuard) -> UserID {
self.value
}
}
}
mod authentication {
use std::marker::PhantomData;
pub struct AuthenticationGuard {
_internal: PhantomData<()>,
}
pub struct AuthenticationProvider {}
impl AuthenticationProvider {
pub const fn do_auth() -> Option<AuthenticationGuard> {
// do something to check the auth
Some(AuthenticationGuard {
_internal: PhantomData,
})
}
}
}
async fn get_balance(user_id: unchecked_input::UncheckedUserID) -> impl IntoResponse {
match authentication::AuthenticationProvider::do_auth() {
Some(guard) => {
let user_id = user_id.ensure_authn(guard);
// go and do some SQL
Json(serde_json::json!({"uid": user_id, "balance": 0.0}))
}
None => Json(serde_json::json!({"error": "auth failure"})),
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/balance/{user_id}", get(get_balance));
let listener = tokio::net::TcpListener::bind("127.0.0.1:8000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}実用性
もちろん、
たとえばstr型のUncheckedStringを
また、
どちらの
UncheckedStringからユーザーに 返す生の 文字列を 取り出すには、 適切な サニタイズが 必要です。 これに より XSSを 緩和できます。 UncheckedStringをSQLクエリに 連結する ことは できません。 これに より、 典型的な SQL脆弱性を 緩和できます。 UncheckedStringをコマンド文字列に 連結する ことは できません。 これに より、 コマンドインジェクションの 脆弱性を 緩和できます。
ほかにもさまざまな
こうした
まとめ
このように
データの
ホワイトペーパー
Python環境に 潜む AIセキュリティの 危機
開発スピードが



